Here is a quick set of functions that will allow you to reboot / shutdown / logoff windows from c#
There is a simple alternative solution but running shell commands from programs isn't always as reliable as calling the api so while something like this will work it really isn't a great solution
System.Diagnostics.Process.Start("shutdown", "-l -t 00");
Some reason why the above won't always work would be
- What if there is a file called shutdown in the current working directory?
(security hole here with network drives) - What if shutdown is not available on the path?
- What if the user does not have permission? (some places only give permissions
to reboot)
So here is a better solution. One that might actually work and as a bonus it will give you all the option available from C#. Just so you are aware I have this in a shared code lib called Stev.Win32 along with a bunch of other Win32 call's.
public static class User32
{
[DllImport("user32.dll")]
public static extern bool ExitWindowsEx(ExitWindowsFlags uFlag, UInt32 dwReserved);
public static bool ExitWindowsEx(ExitWindowsFlags uFlag)
{
return ExitWindowsEx(uFlag, 0);
}
}
[Flags]
public enum ExitWindowsFlags {
EWX_LOGOFF = 0,
EWX_SHUTDOWN = 0x1,
EWX_REBOOT = 0x2,
EWX_FORCE = 0x4,
EWX_POWEROFF = 0x8,
EWX_FORCEIFHUNG = 0x10,
EWX_RESTARTAPPS = 0x40
}
To use it simply call User32.ExitWindowsEx(ExitWindowsFlags.LogOff); You can also alter the options for more control.
Did You find this page useful?
Yes
No