SoFunction
Updated on 2025-03-06

C# delay shutting down the computer and canceling the operation method of shutting down the computer (requires administrator permission)

In C#, if you want to implement the functions of delaying the computer and canceling the shutdown, you can use the following methods.

Please note that these operations require administrator permissions.

Delay shutdown of the computer

AvailableClass to call Windows' shutdown command to achieve delayed shutdown.

Sample code:

using System;
using ;
class Program
{
    static void Main(string[] args)
    {
        int delayMinutes = 5; // Delay time, for example 5 minutes        string shutdownCommand = $"-s -t {delayMinutes * 60}";
        // Call the shutdown command to achieve delayed shutdown        ProcessStartInfo psi = new ProcessStartInfo("shutdown", shutdownCommand);
         = "runas"; // Administrator permission is required        Process process = (psi);
        if (process != null)
        {
            ($"The computer will be in{delayMinutes}Close in minutes。");
        }
        else
        {
            ("The shutdown command cannot be executed, make sure to run this program as an administrator.");
        }
    }
}

Cancel shut down the computer

If you need to provide a way to cancel the previous shutdown command, you can use the following code:

// Cancel the shutdown commandpublic static void CancelShutdown()
{
    ProcessStartInfo cancelPsi = new ProcessStartInfo("shutdown", "-a");
     = "runas"; // Administrator permission is required    Process cancelProcess = (cancelPsi);
    if (cancelProcess != null)
    {
        ("Shutdown has been cancelled.");
    }
    else
    {
        ("The shutdown command cannot be cancelled, make sure to run this program as an administrator.");
    }
}

In the main program, you can call it as neededCancelShutdownMethod to cancel the shutdown task set previously. Remember to make sure that the application has sufficient permissions (usually need to run as an administrator) when performing these operations.

Using Windows API to operate your computer

using System;
using ;
public class Program
{
    // Import ExitWindowsEx functions    [DllImport("", SetLastError = true)]
    private static extern bool ExitWindowsEx(uint uFlags, uint dwReason);
    // Define constants related to shutdown, restart, and cancellation    const uint EWX_LOGOFF = 0x00000000; // Log out    const uint EWX_SHUTDOWN = 0x00000001; // Turn off the power and turn off the power    const uint EWX_REBOOT = 0x00000002; // Restart    const uint EWX_POWEROFF = 0x00000008; // Shut down (no restart)    const uint SHTDN_REASON_MAJOR_APPLICATION = 0x00030000; // Reason for shutting down the application    const uint SHTDN_REASON_MINOR_MAINTENANCE = 0x00000004; // Reason for maintaining shutdown    public static void Main(string[] args)
    {
        // Decide the operation according to the command line parameters        string action = "shutdown"; // Default is shutdown        if ( > 0)
        {
            action = args[0].ToLower();
        }
        uint flags;
        switch (action)
        {
            case "logoff":
                flags = EWX_LOGOFF;
                ("The computer will perform the logout operation...");
                break;
            case "restart":
                flags = EWX_REBOOT;
                ("The computer will perform a restart...");
                break;
            case "shutdown":
                flags = EWX_POWEROFF; // Or use EWX_SHUTDOWN depends on whether the power is required to be turned off                ("The computer will perform a shutdown operation...");
                break;
            default:
                ("Unknown operation. Supported operations are: logoff, restart, shutdown");
                return;
        }
        // Perform an operation        if (ExitWindowsEx(flags | SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_MINOR_MAINTENANCE, 0))
        {
            ($"The operation has started...");
        }
        else
        {
            ("The operation request failed. Please check the error code.");
        }
    }
}

Things to note and how to deal with

  • These operations have a direct impact on the system, please use them with caution.
  • In terms of user experience, it is best to give users clear notifications and confirmations before performing such operations.
  • The above code example applies to Windows operating systems, and other operating systems may not be applicable.

If the program runs without administrator privileges, there are several ways to deal with it:

  • Prompt the user to rerun the program as administrator: Check whether you have administrator privileges when the program starts. If not, the user is prompted to close the program and restart as administrator. This can be checked().OwnerOr try to access resources that require administrator privileges to make an indirect judgment.
  • Require administrator permissions in program manifest file: On the project.csprojFound in the same level directoryFile (if not, you can right-click the project -> Add -> New Item -> Application List File), edit the file, in<requestedExecutionLevel>Settings in the taglevel="requireAdministrator", make sure that the program always runs as an administrator. For example:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

Dynamically request elevated permissions in code: Although this is not a feature directly supported by C#, it can be implemented indirectly by starting a new process and requiring that process to run with administrator privileges. However, this method is more complicated, and the user experience may not be as good as requiring users to run programs as administrators.

It is important that when a program needs to perform operations that affect the system level, it is important to explicitly inform the user and make sure that these operations meet the user's expectations to avoid misoperation or security issues.

This is the article about how to close the computer in C# and cancel the computer in a delayed manner. For more related content on C# and delayed computer in a delayed manner, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!