使用shutdown.exe cmd C#取消PC ShutDown

时间:2014-09-21 17:18:50

标签: c# .net winforms

我在WinForms应用程序中使用此命令来关闭我的PC:

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

此时Windows 8和8.1显示一条消息,告诉我我的电脑将在1分钟后关机。没有选择取消。

我怎样才能(在1分钟内)向cmd / shutdown.exe发送命令以取消关闭PC

3 个答案:

答案 0 :(得分:7)

尝试关闭/ a

如果在时间限制内发送,/ a命令应该中止关机。

查看Technet关于关机的文档:http://technet.microsoft.com/en-us/library/bb491003.aspx

答案 1 :(得分:1)

您可以使用 pinvoke 取消关机(在CancelShutdown中调用user32.dll),而不是调用其他进程。

请参阅:http://www.pinvoke.net/default.aspx/user32/CancelShutdown.html

这相当于shutdown /a正在做的事情。

答案 2 :(得分:1)

您可以通过P / Invokes启动和中止系统关闭advapi32。请参阅InitiateSystemShutdownExAbortSystemShutdown。启动和取消系统关闭都需要SeShutdownPrivilege在本地关闭计算机,或SeRemoteShutdownPrivilege通过网络关闭计算机。

考虑到特权时,完整代码应如下所示。注意:这假定使用System.Security.AccessControl.Privelegewas 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);
}
相关问题