以下是使用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 編輯過