C#代码关闭Windows XP

来源:互联网 发布:淘宝店主写错发货地址 编辑:程序博客网 时间:2024/05/17 08:17
using System;<br />using System.Runtime.InteropServices;<br /> <br />class shoutdown{<br /> [StructLayout(LayoutKind.Sequential, Pack=1)]<br /> internal struct TokPriv1Luid<br /> {<br /> public int Count;<br /> public long Luid;<br /> public int Attr;<br /> }<br /> [DllImport(&quot;kernel32.dll&quot;, ExactSpelling=true) ]<br /> internal static extern IntPtr GetCurrentProcess();<br /> [DllImport(&quot;advapi32.dll&quot;, ExactSpelling=true, SetLastError=true) ]<br /> internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr phtok );<br /> [DllImport(&quot;advapi32.dll&quot;, SetLastError=true) ]<br /> internal static extern bool LookupPrivilegeValue( string host, string name, ref long pluid );<br /> [DllImport(&quot;advapi32.dll&quot;, ExactSpelling=true, SetLastError=true) ]<br /> internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall,<br />ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen );<br /> [DllImport(&quot;user32.dll&quot;, ExactSpelling=true, SetLastError=true) ]<br /> internal static extern bool ExitWindowsEx( int flg, int rea );<br /> internal const int SE_PRIVILEGE_ENABLED = 0x00000002;<br /> internal const int TOKEN_QUERY = 0x00000008;<br /> internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;<br /> internal const string SE_SHUTDOWN_NAME = &quot;SeShutdownPrivilege&quot;;<br /> internal const int EWX_LOGOFF = 0x00000000;<br /> internal const int EWX_SHUTDOWN = 0x00000001;<br /> internal const int EWX_REBOOT = 0x00000002;<br /> internal const int EWX_FORCE = 0x00000004;<br /> internal const int EWX_POWEROFF = 0x00000008;<br /> internal const int EWX_FORCEIFHUNG = 0x00000010;<br /> private static void DoExitWin(int flg)<br /> {<br /> bool ok;<br /> TokPriv1Luid tp;<br /> IntPtr hproc = GetCurrentProcess();<br /> IntPtr htok = IntPtr.Zero;<br /> ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok );<br /> tp.Count = 1;<br /> tp.Luid = 0;<br /> tp.Attr = SE_PRIVILEGE_ENABLED;<br /> ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid );<br /> ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero );<br /> ok = ExitWindowsEx( flg, 0 );<br /> }<br /> public static void Main()<br /> {<br /> Console.WriteLine(&quot;正在关闭计算机&hellip;&hellip;&quot;);<br /> // 修改 EWX_SHUTDOWN 或者 EWX_LOGOFF, EWX_REBOOT等实现不同得功能。<br /> // 在XP下可以看到帮助信息,以得到不同得参数<br /> // SHUTDOWN /?<br /> DoExitWin(EWX_SHUTDOWN);<br /> }}
原创粉丝点击