SoFunction
Updated on 2025-03-06

Detailed explanation of the code for C# to implement Windows system restart and shutdown

1. Use shutdown command to implement it

using ;

 int time = 3600;//Units are: seconds ("c:/windows/system32/", "-s -t "+time);

Implementation principle, use the system shutdown command to execute:

Force shutdown:

shutdown -s -f -t 0

Forced restart:

shutdown -r -f -t 0

Detailed explanation of the shutdown command:

Usage: shutdown [-i | -l | -s | -r | -a] [-f] [-m computername] [-t xx] [-c “comment”] [-d up:xx:yy]

No parameters This message is displayed (same as ?)

-i Display the GUI interface, must be the first option

-l Logout (cannot be used with option -m)

-s Close this computer

-r Close and restart this computer

-a Give up the system shutdown

-m computername Remote computer shutdown/restart/discard

-t xx Set the timeout for off to xx seconds

-c "comment" closes comments (up to 127 characters)

-f Forced running application to close without warning

-d [ u ][p]:xx:yy Close reason code

u is user code

p is a planned close code

xx is a main reason code (positive integers smaller than 256)

yy is a secondary reason code (a positive integer less than 65536)

-f: Forced close the application

-m Computer name: Control the remote computer

-i: Show the graphical user interface, but must be the first option of Shutdown

-l: Log out the current user

-r: Shut down and restart

-t Time: Set the shutdown countdown

-c "Message Content": Enter the message content in the shutdown dialog box (cannot exceed 127 characters)

For example, if your computer wants to shut down at 12:00, you can select "Start → Run" and enter "at 12:00 Shutdown -s". In this way, the computer will have a "System Shutdown" dialog box at 12 o'clock. The default countdown is 30 seconds and prompts you to save your work.

If you want to shut down in a countdown mode, you can enter "-s -t 3600", which means that the power will be automatically shut down after 60 minutes, and "3600" means 60 minutes.

One-click shutdown:

1. First, right-click the blank space on the desktop and create a new "shortcut".

2. Enter the following command in the "Command Line" where you create a shortcut:

"shutdown –s –t 0". (Click here to enter "C: user,ExitWindows" in Windows98.)

3. Press the mouse to select "Next", and enter "One-click shutdown" or other names you like in the name bar of the shortcut.

4. After that, you will see a shortcut icon called "One-click shutdown" on the desktop. Right-click the icon, select "Properties", and then enter the "Shortcut" page, and then press Select a function key in the "Quick Key column (such as F1-F12). It is recommended that you choose a function key that is not commonly used, and finally press OK to exit.

The Windows system completes the shutdown operation through a program called (under Windows\System32). Generally speaking, the shutdown of the Windows system can be achieved by the shutdown program and is called during shutdown. From this we can see that to prevent forced shutdown, we must cancel the right call.

Use C# code to implement methods to control the shutdown, restart and logout of Windows systems. Using .NET and C#.NET, we can perform shutdown, restart and logout operations on the current PC.

In the .NET Framework, there is a namespace with the required classes and methods to run the .NET application from the current PC to perform these operations. Generally, the () method is used to start the program.

Example:

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            //Restart the computer            // (UFlag.EWX_REBOOT);//This method is invalid          string ss=  ("shutdown -r -t 2");
            (ss);
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            //Login the computer            (UFlag.EWX_LOGOFF);
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            //Shut down the computer            // (UFlag.EWX_SHUTDOWN);//Invalid           string ss= ("shutdown -s -t 2");
            (ss);
        }
 
        private void button4_Click(object sender, EventArgs e)
        {
            string ss = ("shutdown -a");
            (ss);
        }
    }
    /// <summary>
    /// PC operation function code    /// </summary>
    enum UFlag
    {
        /// <summary>
        /// Force terminate unresponsive processes        /// </summary>
        EWX_FORCE=4,
        /// <summary>
        /// Log out        /// </summary>
        EWX_LOGOFF=0,
        /// <summary>
        /// Restart        /// </summary>
        EWX_REBOOT=2,
        /// <summary>
        /// Turn off the system        /// </summary>
        EWX_SHUTDOWN=1
    }
    class APIHelper
    {
        /// <summary>
        /// Use the dos command to operate        /// </summary>
        /// <param name="cmdStr"></param>
        /// <returns></returns>
        public static string DOSCommand(string cmdStr)
        {
             info = new ();
             =true;//Do not display black window             = "";
             = true;
             = true;
             = true;
             = false;
            var p = (info);
            //Treatment method 1:            //using ( tw= )
            //{
            //    (cmdStr);
            //}
            
            //Processing method 2: Add:&exit after the instruction.            (cmdStr + "&exit");
          
            ();
            string str = "";
            using ( tr = )
            {
                str = ();
            }
 
            ();
            return str;
        }
        public static int ExitWindows(UFlag flag)
        {
            return ExitWindowsEx((int)flag, 0);
        }
        /// <summary>
        /// Log out, close, restart the computer        /// </summary>
        /// <param name="uFlag">Operation to be performed</param>        /// <param name="dwReserved">Reserved value, generally set to 0</param>        /// &lt;returns&gt;&lt;/returns&gt;
        [DllImport("")]
         extern static int ExitWindowsEx(int uFlag, int dwReserved);
        
    }

For specific usage methods, please refer to the command line instructions. This method can be used on a PC, but when the system is WINCE, WINCE does not, so the method will no longer be used. A second method can be used.

2. Call the WIN32 API to implement it

using System;
using ;
using ;
using ;

namespace TestShutdown
{
    class SystemUtil
    {
        [StructLayout(, Pack = 1)]
        internal struct TokPriv1Luid
        {
            public int Count;
            public long Luid;
            public int Attr;
        }

        [DllImport("", ExactSpelling = true)]
        internal static extern IntPtr GetCurrentProcess();

        [DllImport("", ExactSpelling = true, SetLastError = true)]
        internal static extern bool OpenProcessToken(IntPtr h, int acc, ref   IntPtr phtok);

        [DllImport("", SetLastError = true)]
        internal static extern bool LookupPrivilegeValue(string host, string name, ref   long pluid);

        [DllImport("", ExactSpelling = true, SetLastError = true)]
        internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen);

        [DllImport("", ExactSpelling = true, SetLastError = true)]
        internal static extern bool ExitWindowsEx(int flg, int rea);

        internal const int SE_PRIVILEGE_ENABLED = 0x00000002;
        internal const int TOKEN_QUERY = 0x00000008;
        internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
        internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
        internal const int EWX_LOGOFF = 0x00000000;
        internal const int EWX_SHUTDOWN = 0x00000001;
        internal const int EWX_REBOOT = 0x00000002;
        internal const int EWX_FORCE = 0x00000004;
        internal const int EWX_POWEROFF = 0x00000008;
        internal const int EWX_FORCEIFHUNG = 0x00000010;

        private static void DoExitWin(int flg)
        {
            bool ok;
            TokPriv1Luid tp;
            IntPtr hproc = GetCurrentProcess();
            IntPtr htok = ;
            ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref   htok);
             = 1;
             = 0;
             = SE_PRIVILEGE_ENABLED;
            ok = LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref   );
            ok = AdjustTokenPrivileges(htok, false, ref   tp, 0, , );
            ok = ExitWindowsEx(flg, 0);
        }

        public static void Reboot()
        {
            DoExitWin(EWX_FORCE | EWX_REBOOT); //Restart        }

        public static void PowerOff()
        {
            DoExitWin(EWX_FORCE | EWX_POWEROFF);    //Shut down        }

        public static void LogoOff()
        {
            DoExitWin(EWX_FORCE | EWX_LOGOFF);      //Login        }

    }

}

The above is the detailed explanation of the code for C# to implement Windows system restart and shutdown. For more information about C# windows restart and shutdown, please pay attention to my other related articles!