C#实现关机、重启、注销

01       <PRE class=brush:csharp;collapse:true;>        //实现关机,重启,注销
02        [StructLayout(LayoutKind.Sequential, Pack = 1)]
03        internal struct TokPriv1Luid
04        
05            public int Count;
06            public long Luid;
07            public int Attr;
08        
09  
10        //[DllImport]允许.NET调用任意非托管的C/C++基类库,包括操作系统中的API.但与基于COM的软件通信时,[DLLImport]不能使用.
11        [DllImport("kernel32.dll", ExactSpelling = true)]
12        internal static extern IntPtr GetCurrentProcess();
13  
14        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
15        internal static extern bool OpenProcessToken(IntPtr h, int acc, ref   IntPtr phtok);
16  
17        [DllImport("advapi32.dll", SetLastError = true)]
18        internal static extern bool LookupPrivilegeValue(string host, string name, ref   long pluid);
19  
20        [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
21        internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall,
22        ref   TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);
23  
24        [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)]
25        internal static extern bool ExitWindowsEx(int flg, int rea);
26  
27        internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
28        internal const int TOKEN_QUERY = 0x00000008;
29        internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
30        internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
31        internal const int EWX_LOGOFF = 0x00000000;
32        internal const int EWX_SHUTDOWN = 0x00000001;
33        internal const int EWX_REBOOT = 0x00000002;
34        internal const int EWX_FORCE = 0x00000004;
35        internal const int EWX_POWEROFF = 0x00000008;
36        internal const int EWX_FORCEIFHUNG = 0x00000010;
37  
38        private static void DoExitWin(int flg)
39        
40            bool ok;
41            TokPriv1Luid tp;
42            IntPtr hproc = GetCurrentProcess();
43            IntPtr htok = IntPtr.Zero;
44            ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref   htok);
45            tp.Count = 1;
46            tp.Luid = 0;
47            tp.Attr = SE_PRIVILEGE_ENABLED;
48            ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref   tp.Luid);
49            ok = AdjustTokenPrivileges(htok, falseref   tp, 0, IntPtr.Zero, IntPtr.Zero);
50            ok = ExitWindowsEx(flg, 0);
51        
52  
53        //重启
54        public void Reboot()
55        
56            DoExitWin(EWX_FORCE | EWX_REBOOT);
57        
58  
59        //关机
60        public void PowerOff()
61        
62            DoExitWin(EWX_FORCE | EWX_POWEROFF);
63        
64  
65        //注销
66        public static void LogoOff()
67        
68            DoExitWin(EWX_FORCE | EWX_LOGOFF);
69        
70  
71</PRE>
72<BR>        }<BR><BR>
posted @ 2014-06-08 10:49  zzg168  阅读(232)  评论(0)    收藏  举报