Question

Possible Duplicate:
How to shutdown the computer from C#

I want to bring up a restart computer message box after an event occurs in my Win Form application. What command can I use to restart the computer if the user chooses Yes?

No correct solution

OTHER TIPS

You can p/invoke ExitWindowsEx.

As noted, you'll need to call AdjustTokenPrivileges as well, since SE_SHUTDOWN_NAME is inactive by default.

A whole bunch of information available on MSDN here

you should use WINAPI . the below function can do power task for you :

BOOL WINAPI ExitWindowsEx(
  _In_  UINT uFlags,
  _In_  DWORD dwReason
);

Note that this function is in user32.dll. Simply to restart :

ExitWindowsEx(2,4);

Here is the full list of flags : link to msdn

Now here is sample C# Code for this :

using System.Runtime.InteropServices;

[DllImport("user32.dll", SetLastError=true)]

public static extern bool  ExitWindowsEx(uint uFlags,uint dWReason);


public static void Main()
{
  ExitWindowsEx(2,4);
}
Process.Start("shutdown","/r /t 0");

This particular solution worked for me: https://stackoverflow.com/a/102583/1505128

using System.Management;

void Shutdown()
{
    ManagementBaseObject mboShutdown = null;
    ManagementClass mcWin32 = new ManagementClass("Win32_OperatingSystem");
    mcWin32.Get();

    // You can't shutdown without security privileges
    mcWin32.Scope.Options.EnablePrivileges = true;
    ManagementBaseObject mboShutdownParams =
             mcWin32.GetMethodParameters("Win32Shutdown");

    // Flag 1 means we want to shut down the system. Use "2" to reboot.
    mboShutdownParams["Flags"] = "1";
    mboShutdownParams["Reserved"] = "0";
    foreach (ManagementObject manObj in mcWin32.GetInstances())
    {
        mboShutdown = manObj.InvokeMethod("Win32Shutdown", 
                                       mboShutdownParams, null);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top