C#实现Windows7/8/10/11系统强制重启代码
|
admin
2025年5月12日 20:46
本文热度 66
|
以下是使用C#实现强制重启Windows 11操作系统的代码示例,提供两种常见方法:
方法1:调用系统命令(推荐)
using System;
using System.Diagnostics;
public class SystemRebooter{
public static void ForceReboot()
{
try
{
// 使用shutdown命令强制重启
var psi = new ProcessStartInfo
{
FileName = "shutdown.exe",
Arguments = "/r /f /t 0", // 立即强制重启
UseShellExecute = false,
CreateNoWindow = true
};
Process.Start(psi);
}
catch (System.ComponentModel.Win32Exception ex)
{
// 处理权限不足的情况
Console.WriteLine($"需要管理员权限: {ex.Message}");
}
}
}
// 使用示例
SystemRebooter.ForceReboot();
方法2:使用Windows API(更底层)
using System;
using System.Runtime.InteropServices;
public class SystemRebooter{
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtRaiseHardError(
int ErrorStatus,
int NumberOfParameters,
int UnicodeStringParameterMask,
IntPtr Parameters,
int ValidResponseOption,
out int Response);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool InitiateSystemShutdownEx(
string lpMachineName,
string lpMessage,
uint dwTimeout,
bool bForceAppsClosed,
bool bRebootAfterShutdown,
uint dwReason);
public static void ForceReboot()
{
// 方法1: 通过系统关机API
InitiateSystemShutdownEx(
null, // 本机
"强制重启", // 显示消息
0, // 立即执行
true, // 强制关闭程序
true, // 重启
0x80000000); // 原因代码
// 方法2: 通过硬错误触发(仅作技术演示)
// int response;
// NtRaiseHardError(0xC000021C, 0, 0, IntPtr.Zero, 6, out response);
}
}
// 使用示例
SystemRebooter.ForceReboot();
注意事项:
管理员权限:两种方法都需要以管理员身份运行程序
在Visual Studio中:右键项目 → 添加 → 新建项 → 应用程序清单文件 → 修改
<requestedExecutionLevel level="requireAdministrator"/>
已编译的程序:右键exe → 属性 → 兼容性 → 勾选"以管理员身份运行"
数据丢失警告:强制重启不会保存未保存的工作,谨慎使用
Windows版本:代码适用于Windows 7/8/10/11全系版本
安全软件拦截:部分安全软件可能会阻止强制重启操作
建议优先使用方法1,因为:
如果需要更底层的控制(如自定义关机原因代码),可以使用方法2中的API方式。实际开发中建议添加用户确认对话框和日志记录功能。
该文章在 2025/5/12 20:46:30 编辑过