jay_t55
jay_t55

Reputation: 11662

Cancel PC ShutDown using shutdown.exe cmd C#

I'm using this command in a WinForms app to shutdown my PC:

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

at which point Windows 8 and 8.1 displays a message telling me that my PC will shutdown in 1 minute. With no option to cancel.

How can I then (within that 1 minute) send a command to cmd/shutdown.exe to cancel shutting down the PC?

Upvotes: 0

Views: 826

Answers (3)

Mitch
Mitch

Reputation: 22311

You can initiate and abort system shutdowns via P/Invokes to advapi32. See InitiateSystemShutdownEx and AbortSystemShutdown. Initiating and cancelling system shutdowns both require SeShutdownPrivilege to shut down the computer locally, or SeRemoteShutdownPrivilege to shut down the computer over the network.

The complete code should look like the below when privileges are taken into account. Note: this assumes use of the System.Security.AccessControl.Privelege class, which was released in an MSDN magazine article, available for download 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);
}

Upvotes: 1

Simon Laing
Simon Laing

Reputation: 1214

You could use pinvoke to cancel the shutdown (calling CancelShutdown in user32.dll), rather than invoking another process.

See: http://www.pinvoke.net/default.aspx/user32/CancelShutdown.html

This is equivalent to what shutdown /a is doing.

Upvotes: 1

NinjaMid76
NinjaMid76

Reputation: 169

Try shutdown /a

The /a command should abort the shutdown if it's sent within the time limit.

Check out Technet's documentation on Shutdown: http://technet.microsoft.com/en-us/library/bb491003.aspx

Upvotes: 7

Related Questions