.NET doesn’t support rebooting, logging off or shutting down your computer though a managed API. Searching for the best way to do this brings up three options: WMI, shutdown.exe and ExitWindowsEx.
I regard WMI as the last resort of the desperate. Weakly typed magic string juju.
Calling Process.Start(“shutdown.exe /r /t 0”) might work, but how would you know? And you’ve got the overheard of starting a new process just to accomplish a reboot. Lazy.
The best way to reboot is P/Invoke to ExitWindowsEx. Unfortunately there’s some really awful sample code out there which will either fail to do anything or mask any errors. I’ve included a drop-in class below that fixes these problems.
If you read all the way through the documentation for ExitWindowsEx you’ll find this:
To shut down or restart the system, the calling process must use the AdjustTokenPrivileges function to enable the SE_SHUTDOWN_NAME privilege. For more information, see Running with Special Privileges.
So just calling ExitWindowsEx won’t do anything. The sample code below adjusts the process token and then reboots (change the flags passed to ExitWindowsEx to shutdown instead, or to pass in a different reason). You’ll also get a Win32Exception if a failure occurs. Catch this, and you can tell the user that they need to reboot manually.
Video timeout on XP and Vista (power management) — I'm updating a screensaver so that it stops work once the monitor switches off. This seemed like a really simple requirement but it took some time to find an API that works on both XP and Vista. My first attempt was ReadPwrScheme(). The...
UAC shield icon in WPF — WPF: When it's good it’s very, very good and when it’s bad it’s like sautéing your own eyeballs. When you’re about to launch a process that will trigger an elevation prompt it’s polite to decorate it with the little UAC shield so the user knows what to...
WiX Tricks for Screen Savers — I've been migrating my installers over to WiX. My only complaint with the WiX toolkit is that there's no bootstrapper included. This is important for installing any pre-requisites before passing control over to Windows Installer. Hopefully this will...