3

I've done a fair bit of googling and always seem to come back to the same solution, which just doesn't seem to work !

private void btnRestart_Click(object sender, EventArgs e)
{
    System.Diagnostics.Process.Start("Shutdown.exe", "/r /f /t 00");
}

private void btnShutdown_Click(object sender, EventArgs e)
{
    System.Diagnostics.Process.Start("Shutdown.exe", "/s /f /t 00");
}

The CMD appears for a brief second and then closes, without doing anything. Am I missing something?

chtenb
  • 14,924
  • 14
  • 78
  • 116
PnP
  • 3,133
  • 17
  • 62
  • 95

5 Answers5

1

This is a bit cleaner

using System.Runtime.InteropServices;

[DllImport("user32.dll", SetLastError = true)]
static extern int ExitWindowsEx(uint uFlags, uint dwReason);

ExitWindowsEx(1, 0); //this will cause the system to shut down.

ExitWindowsEx(2, 0); //this will cause the system to reboot.
Chuck
  • 1,001
  • 1
  • 13
  • 19
0

add these namespace to your code

    using System.Diagnostics;
    using System.Runtime.InteropServices;

And even it depends on what privileges you are assigned. I hope this will help you.

Gourav
  • 1,765
  • 2
  • 15
  • 16
  • @FrK reference the link http://stackoverflow.com/questions/102567/how-to-shutdown-the-computer-from-c-sharp – Gourav Sep 15 '13 at 10:48
0

According to shutdown /?, you don't use slashes (/) but dashes(-).

Or, try to run cmd.exe with params /c shutdown.exe /r /f /t 00

Levente Kurusa
  • 1,858
  • 14
  • 18
0

Try passing arguments with ProcessStartInfo:

ProcessStartInfo startInfo = new ProcessStartInfo("shutdown.exe");
startInfo.Arguments = "/r /f /t 00";
Process.Start(startInfo);
Alberto
  • 15,626
  • 9
  • 43
  • 56
0

This answer i got it from HERE.It works for me.make sure to add a reference to System.Management

 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);
        }
    }
Thilina H
  • 5,754
  • 6
  • 26
  • 56