1. using System; 
  2. using System.Runtime.InteropServices; 

  3. class shoutdown{ 
  4.    [StructLayout(LayoutKind.Sequential, Pack=1)] 
  5.    internal struct TokPriv1Luid 
  6.    { 
  7.       public int Count; 
  8.       public long Luid; 
  9.       public int Attr; 
  10.    } 

  11.    [DllImport("kernel32.dll", ExactSpelling=true) ] 
  12.    internal static extern IntPtr GetCurrentProcess(); 

  13.    [DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ] 
  14.    internal static extern bool OpenProcessToken( IntPtr h, int acc, ref IntPtr phtok ); 

  15.    [DllImport("advapi32.dll", SetLastError=true) ] 
  16.    internal static extern bool LookupPrivilegeValue( string host, string name, ref long pluid ); 

  17.    [DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true) ] 
  18.    internal static extern bool AdjustTokenPrivileges( IntPtr htok, bool disall, 
  19. ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen ); 

  20.    [DllImport("user32.dll", ExactSpelling=true, SetLastError=true) ] 
  21.    internal static extern bool ExitWindowsEx( int flg, int rea ); 

  22.    internal const int SE_PRIVILEGE_ENABLED = 0x00000002; 
  23.    internal const int TOKEN_QUERY = 0x00000008; 
  24.    internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; 
  25.    internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege"; 
  26.    internal const int EWX_LOGOFF = 0x00000000; 
  27.    internal const int EWX_SHUTDOWN = 0x00000001; 
  28.    internal const int EWX_REBOOT = 0x00000002; 
  29.    internal const int EWX_FORCE = 0x00000004; 
  30.    internal const int EWX_POWEROFF = 0x00000008; 
  31.    internal const int EWX_FORCEIFHUNG = 0x00000010; 

  32.    private static void DoExitWin(int flg) 
  33.    { 
  34.       bool ok; 
  35.       TokPriv1Luid tp; 
  36.       IntPtr hproc = GetCurrentProcess(); 
  37.       IntPtr htok = IntPtr.Zero; 
  38.       ok = OpenProcessToken( hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok ); 
  39.       tp.Count = 1; 
  40.       tp.Luid = 0; 
  41.       tp.Attr = SE_PRIVILEGE_ENABLED; 
  42.       ok = LookupPrivilegeValue( null, SE_SHUTDOWN_NAME, ref tp.Luid ); 
  43.       ok = AdjustTokenPrivileges( htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero ); 
  44.       ok = ExitWindowsEx( flg, 0 ); 
  45.    } 

  46.       public static void Main() 
  47.       { 
  48.          Console.WriteLine("正在关机……"); 
  49.          // 修改 EWX_SHUTDOWN 或者 EWX_LOGOFF, EWX_REBOOT等实现不同得功能。 
  50.          // 在XP下可以看到帮助信息,以得到不同得参数 
  51.          // SHUTDOWN /? 
  52.          DoExitWin(EWX_SHUTDOWN); 
  53.       }