Home
Manage Your Code
Snippet: Windows Shutdown from .NET (C#)
Title: Windows Shutdown from .NET Language: C#
Description: Code to shutdown windows from a .NET application. Views: 867
Author: Daniel Schless Date Added: 8/27/2007
Copy Code  
1	public class Win32
2	{
3		public static void Reboot()
4		{
5			adjustToken();
6			ExitWindowsEx( EWX_SHUTDOWN | EWX_FORCE | EWX_SHUTDOWN, 0xFFFF );
7		}
8		private static void adjustToken()
9		{
10			TOKEN_PRIVILEGES tkp;
11			IntPtr hproc = GetCurrentProcess();
12			IntPtr htok = IntPtr.Zero;
13
14			OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );
15			tkp.Count = 1;
16			tkp.Luid = 0;
17			tkp.Attr = SE_PRIVILEGE_ENABLED;
18
19			LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tkp.Luid );
20			AdjustTokenPrivileges( htok, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero );
21		}
22
23		[StructLayout( LayoutKind.Sequential, Pack = 1 )]
24		internal struct TOKEN_PRIVILEGES
25		{
26			public int Count;
27			public long Luid;
28			public int Attr;
29		}
30
31		internal const int EWX_SHUTDOWN = 0x00000001;
32		internal const int EWX_REBOOT = 0x00000002;
33		internal const int EWX_FORCE = 0x00000004;
34
35		[DllImport( "kernel32.dll", ExactSpelling = true )]
36		internal static extern IntPtr GetCurrentProcess();
37
38		[DllImport( "advapi32.dll", ExactSpelling = true, SetLastError = true )]
39		internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
40
41		[DllImport( "advapi32.dll", SetLastError = true )]
42		internal static extern bool LookupPrivilegeValue(string host, string name, ref long pluid);
43
44		[DllImport( "advapi32.dll", ExactSpelling = true, SetLastError = true )]
45		internal static extern bool AdjustTokenPrivileges(IntPtr htok,
46														  bool disall,
47														  ref TOKEN_PRIVILEGES newst,
48														  int len,
49														  IntPtr prev,
50														  IntPtr relen);
51
52		[DllImport( "user32.dll", ExactSpelling = true, SetLastError = true )]
53		internal static extern bool ExitWindowsEx(int flg, int rea);
54
55		internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
56		internal const int TOKEN_QUERY = 0x00000008;
57		internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
58		internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
59	}
60
Usage
Win32.Reboot();