What's the best way to shut down the computer from a C# program?
I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.
What's the best way to shut down the computer from a C# program?
I've found a few methods that work - I'll post them below - but none of them are very elegant. I'm looking for something that's simpler and natively .net.
The old-school ugly method. Use the
ExitWindowsEx
function from the Win32 API.In production code you should be checking the return values of the API calls, but I left that out to make the example clearer.
Short and sweet. Call an external program:
Note: This calls Windows' Shutdown.exe program, so it'll only work if that program is available. You might have problems on Windows 2000 (where shutdown.exe is only available in the resource kit) or XP Embedded.
Should work.
For restart, it's /r
This will restart the PC box directly and cleanly, with NO dialogs.
Taken from: a Geekpedia post
This method uses WMI to shutdown windows.
You'll need to add a reference to System.Management to your project to use this.
I had trouble trying to use the WMI method accepted above because i always got privilige not held exceptions despite running the program as an administrator.
The solution was for the process to request the privilege for itself. I found the answer at http://www.dotnet247.com/247reference/msgs/58/292150.aspx written by a guy called Richard Hill.
I've pasted my basic use of his solution below in case that link gets old.
There is no .net native method for shutting off the computer. You need to P/Invoke the ExitWindows or ExitWindowsEx API call.