现在的位置: 首页 > 综合 > 正文

C# 关机程序

2013年06月24日 ⁄ 综合 ⁄ 共 2283字 ⁄ 字号 评论关闭
  1. using System; 
  2. using System.Runtime.InteropServices; 
  3.    
  4. class shoutdown{ 
  5.    [StructLayout(LayoutKind.Sequential, Pack=1)] 
  6.    internal struct TokPriv1Luid 
  7.    { 
  8.       public int Count; 
  9.       public long Luid; 
  10.       public int Attr; 
  11.    } 
  12.    [DllImport("kernel32.dll", ExactSpelling=true) ] 
  13.    internal static extern IntPtr GetCurrentProcess(); 
  14.    [DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ] 
  15.    internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr phtok ); 
  16.    [DllImport("advapi32.dll", SetLastError=true) ] 
  17.    internal static extern bool LookupPrivilegeValue( string host, string name, ref long pluid ); 
  18.    [DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ] 
  19.    internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall, 
  20. ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen ); 
  21.    [DllImport("user32.dll", ExactSpelling=true, SetLastError=true) ] 
  22.    internal static extern bool ExitWindowsEx( int flg, int rea ); 
  23.    internal const int SE_PRIVILEGE_ENABLED = 0x00000002; 
  24.    internal const int TOKEN_QUERY = 0x00000008; 
  25.    internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; 
  26.    internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"
  27.    internal const int EWX_LOGOFF = 0x00000000; 
  28.    internal const int EWX_SHUTDOWN = 0x00000001; 
  29.    internal const int EWX_REBOOT = 0x00000002; 
  30.    internal const int EWX_FORCE = 0x00000004; 
  31.    internal const int EWX_POWEROFF = 0x00000008; 
  32.    internal const int EWX_FORCEIFHUNG = 0x00000010; 
  33.    private static void DoExitWin(int flg) 
  34.    { 
  35.       bool ok; 
  36.       TokPriv1Luid tp; 
  37.       IntPtr hproc = GetCurrentProcess(); 
  38.       IntPtr htok = IntPtr.Zero; 
  39.       ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok ); 
  40.       tp.Count = 1; 
  41.       tp.Luid = 0; 
  42.       tp.Attr = SE_PRIVILEGE_ENABLED; 
  43.       ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid ); 
  44.       ok = AdjustTokenPrivileges( htok, falseref tp, 0, IntPtr.Zero, IntPtr.Zero ); 
  45.       ok = ExitWindowsEx( flg, 0 ); 
  46.    } 
  47.       public static void Main() 
  48.       { 
  49.          Console.WriteLine("正在关机……"); 
  50.          // 修改 EWX_SHUTDOWN 或者 EWX_LOGOFF, EWX_REBOOT等实现不同得功能。 
  51.          // 在XP下可以看到帮助信息,以得到不同得参数 
  52.          // SHUTDOWN /? 
  53.          DoExitWin(EWX_SHUTDOWN); 
  54.       } 

抱歉!评论已关闭.