C#闪电关机/重启类
调用ntdll.dll内的 ZwShutdownSystem 函数实现闪电关机/重启的功能
using System;
using System.Runtime.InteropServices;
namespace Biltong_SystemPower
{
public enum Options
{
Poweroff = 2,
Reboot=1
}
public class SystemPower
{
private delegate uint ZwShutdownSystem(int ShutdownAction);
private delegate uint RtlAdjustPrivilege(int Privilege, bool Enable, bool CurrentThread, ref int Enabled);
[DllImport("kernel32.dll")]
private static extern IntPtr LoadLibrary(string path);
[DllImport("kernel32.dll")]
private static extern IntPtr GetProcAddress(IntPtr lib, string funcName);
[DllImport("kernel32.dll")]
private static extern bool FreeLibrary(IntPtr lib);
//将要执行的函数转换为委托
private Delegate Invoke(string APIName, Type t, IntPtr hLib)
{
IntPtr api = GetProcAddress(hLib, APIName);
return (Delegate)Marshal.GetDelegateForFunctionPointer(api, t);
}
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread()]
public void Setup(Int32 Options)
{
IntPtr hLib = LoadLibrary("ntdll.dll");
RtlAdjustPrivilege rtla = (RtlAdjustPrivilege)Invoke("RtlAdjustPrivilege", typeof(RtlAdjustPrivilege), hLib);
ZwShutdownSystem shutdown = (ZwShutdownSystem)Invoke("ZwShutdownSystem", typeof(ZwShutdownSystem), hLib);
int en = 0;
uint ret = rtla(0x13, true, false, ref en);
//SE_SHUTDOWN_PRIVILEGE = 0x13; //关机权限
ret = shutdown(Options);
// POWEROFF = 0x2 // 关机 // REBOOT = 0x1 // 重启
}
}
}

浙公网安备 33010602011771号