2014-09-21 49 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); 
}