通过win表单应用程序重新启动计算机

时间:2013-01-25 00:03:19

标签: c# winforms winapi

  

可能重复:
  How to shutdown the computer from C#

我想在Win Form应用程序中发生事件后调出一个重启计算机消息框。 如果用户选择是,我可以使用什么命令重新启动计算机?

4 个答案:

答案 0 :(得分:3)

你可以p/invoke ExitWindowsEx

如上所述,您还需要拨打AdjustTokenPrivileges,因为SE_SHUTDOWN_NAME默认处于非活动状态。

可用的大量信息on MSDN here

答案 1 :(得分:1)

你应该使用WINAPI。以下功能可以为您执行电源任务:

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

请注意,此功能位于user32.dll中。 只需重新启动:

ExitWindowsEx(2,4);

以下是标志的完整列表:link to msdn

现在这里是示例C#代码:

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

答案 2 :(得分:0)

Process.Start("shutdown","/r /t 0");

答案 3 :(得分:-1)

这个特殊的解决方案对我有用: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);
    }
}