C# - Logoff

7. March 2011 19:49

Here is a quick set of functions that will allow you to reboot / shutdown / logoff windows from c#


I was flicking though some things on another asp.net / c# and stumbled across the following post. It is aimed at providing a solution in VB.NET to reboot a computer. However I think its a pretty poor attempt at solving the problem so I have been digging though my code base and found the following solution.

The original solution looks something like this to logoff a user from a computer.


System.Diagnostics.Process.Start("shutdown", "-l -t 00");


Now you will probably notice that it will actually work. Well most of the time. Here is a list of problems that I can think of with the code above.


  • What if there is a file called shutdown in the current working directory? (security hole here with network drives)
  • What if shutdown is not avilable 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 avilable 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
    public static extern bool ExitWindowsEx(ExitWindowsFlags uFlag, UInt32 dwReserved);

    public static bool ExitWindowsEx(ExitWindowsFlags uFlag)
        return ExitWindowsEx(uFlag, 0);

public enum ExitWindowsFlags {
    EWX_LOGOFF = 0,
    EWX_SHUTDOWN = 0x1,
    EWX_REBOOT = 0x2,
    EWX_FORCE = 0x4,
    EWX_POWEROFF = 0x8,


To use it simply call User32.ExitWindowsEx(ExitWindowsFlags.LogOff); You can also or the options for more control.


As you can see above it really does not take too much more effort to dig though some of the windows documentation to fnid the correct values. It also becomes almost self explaining as to what it is doing and how it works. Though of course you now have no risk of running external programs unexpectedly. You can also get smarter error codes while using this function by calling GetLastError

E-mail Kick it! DZone it! del.icio.us Permalink

Comments (1) -

6/30/2011 2:22:42 PM #

Thanks for this

dejco Slovenia |