2014-09-21 70 views
0

我在WinForms應用程序使用此命令來關閉我的電腦取消PC關機:使用shutdown.exe的CMD C#

System.Diagnostics.Process.Start("shutdown", "/s");

此時Windows 8和8.1顯示一條消息,告訴我,我的PC將在1分鐘內關閉。沒有選擇取消。

我該怎麼辦(在1分鐘內)發送一條命令到cmd/shutdown.exe至取消關閉PC

回答

1

您可以通過P/Invokes啓動和中止系統關閉至advapi32。見InitiateSystemShutdownExAbortSystemShutdown。啓動和取消系統關閉都需要SeShutdownPrivilege關閉本地計算機,或SeRemoteShutdownPrivilege要通過網絡關閉計算機。

當考慮到特權時,完整的代碼應如下所示。注意:這裏假定使用System.Security.AccessControl.Privelege類,其中was released in an MSDN magazine article,可供下載as linked from the article

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] 
public static extern bool InitiateSystemShutdownEx(
    string lpMachineName, 
    string lpMessage, 
    uint dwTimeout, 
    bool bForceAppsClosed, 
    bool bRebootAfterShutdown, 
    uint dwReason); 

[DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] 
public static extern bool AbortSystemShutdown(string lpMachineName); 

public static void Shutdown() 
{ 
    Privilege.RunWithPrivilege(Privilege.Shutdown, true, (_) => 
    { 
     if (!NativeMethods.InitiateSystemShutdownEx(null /* this computer */, 
      "My application really needs to restart", 
      30 /* seconds */, true /* force shutdown */, 
      true /* restart */, 0x4001 /* application: unplanned maintenance */)) 
     { 
      throw new Win32Exception(); 
     } 
    }, null); 
} 

public static void CancelShutdown() 
{ 
    Privilege.RunWithPrivilege(Privilege.Shutdown, true, (_) => 
    { 
     if (!NativeMethods.AbortSystemShutdown(null /* this computer */)) 
     { 
      throw new Win32Exception(); 
     } 
    }, null); 
}