Show Changes Show Changes
Edit Edit
Print Print
Recent Changes Recent Changes
Subscriptions Subscriptions
Lost and Found Lost and Found
Find References Find References
Rename Rename
Search

History

5/4/2005 9:12:53 AM
List all versions List all versions
How To Programmatically Log Off Or Reboot The Machine
.

Logging off logically means ending your logon session (WhatIsALogonSession), which means closing any processes that have tokens (WhatIsAToken) that point to your logon session. Win32 provides a function to do this called ExitWindowsEx. It looks at the logon session of the code that called it and then closes all processes running within that session. If the interactive user is being logged off, the Winlogon desktop will become active afterward. The C# code for this is shown in Figure 73.1.

  using System.Runtime.InteropServices;
    class LogOff {
      static void Main() {
        ExitWindowsEx(0, 0);
      }
    [DllImport("user32.dll")]
    static extern bool ExitWindowsEx(uint flags, uint reason);
  }

Figure 73.1 Forcing a logoff programmatically

You can also force a reboot using ExitWindowsEx, but you must have (and enable) a privilege called SeShutdownPrivilege in order to do that (HowToUseAPrivilege). The C# code for rebooting the machine is shown in Figure 73.2. Note that it uses a helper class that I developed in HowToUseAPrivilege to enable the privilege.

  using System;
  using System.Runtime.InteropServices;
  using KBC.WindowsSecurityUtilities;


  class RebootMachine {
    static void Main() {
      // enable the Shutdown privilege
      try {
        using (Token.EnablePrivilege("SeShutdownPrivilege",
           true)) {
          // reboot - pick a reason code that
          // makes sense for what you're doing
          ExitWindowsEx(EWX_REBOOT,
            SHTDN_REASON_MAJOR_APPLICATION  |
            SHTDN_REASON_MINOR_INSTALLATION |
            SHTDN_REASON_FLAG_PLANNED);
         }
       }
       catch (Exception) {
         Console.WriteLine("You need a privilege"  +
           " to run this program:" +
           " Shut down the system");
         return;
       }
    }
    [DllImport("user32.dll")]
    static extern bool ExitWindowsEx(uint flags, uint reason);


    // from Win32 header file: reason.h
    const uint SHTDN_REASON_MAJOR_APPLICATION  = 0x00040000;
    const uint SHTDN_REASON_MINOR_INSTALLATION = 0x00000002;
    const uint SHTDN_REASON_FLAG_PLANNED       = 0x80000000;


    // from Win32 header file: winuser.h
    const uint EWX_REBOOT = 0x00000002;
  }

Figure 73.2 Forcing a reboot programmatically

PluralsightTraining

Keith's first book-in-a-wiki. If you would like to read the book online or order a physical copy to throw at annoying coworkers, surf to the HomePage. Please note that due to overwhelming wikispam, this particular wiki is no longer editable.

About FlexWiki.

Recent Topics