按钮上的关闭或重新启动本地计算机

时间:2013-09-15 10:37:03

标签: c#

我已经做了相当多的谷歌搜索,似乎总是回到相同的解决方案,这似乎不起作用!

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");
}

CMD短暂出现然后关闭,没有做任何事情。我错过了什么吗?

5 个答案:

答案 0 :(得分:1)

这有点清洁



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.




答案 1 :(得分:0)

将这些命名空间添加到您的代码中

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

甚至取决于您分配的权限。 我希望这会对你有所帮助。

答案 2 :(得分:0)

根据shutdown /?,你不要使用斜杠(/)而是破折号( - )。

或者,尝试使用参数cmd.exe

运行/c shutdown.exe /r /f /t 00

答案 3 :(得分:0)

尝试使用ProcessStartInfo:

传递参数
ProcessStartInfo startInfo = new ProcessStartInfo("shutdown.exe");
startInfo.Arguments = "/r /f /t 00";
Process.Start(startInfo);

答案 4 :(得分:0)

这个答案我是从HERE得到的。它适用于我。确保添加对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);
        }
    }