用C#实现快速关机

首先我们用RtlAdjustPrivilege获取系统最高权限SeDebugPrivilege

        [DllImport("ntdll.dll")]
        private static extern uint RtlAdjustPrivilege(
       int Privilege,
       bool bEnablePrivilege,
       bool IsThreadPrivilege,
       out bool PreviousValue
   );

声明NtShutdownSystem API

    [DllImport("ntdll.dll")]
    private static extern uint NtShutdownSystem([In]uint Action);

其中的Action有三个 0表示ShutdownNoReboot(强制直接关机),

1表示ShutdownReboot(调用BIOS Reset) ,

2表示ShutdownPowerOff(调用BIOS Shutdown)

接下来开始获取权限关机

bool previousValue;
RtlAdjustPrivilege(19, true, false, out previousValue);
NtShutdownSystem(0);

通常能在3秒左右关机,但是这样关机不会通知运行的程序,所以未保存的信息会丢失。谨慎使用。


以下是RtlAdjustPrivilege的权限列表。

SeCreateTokenPrivilege              =   1
SeAssignPrimaryTokenPrivilege       =   2
SeLockMemoryPrivilege               =   3
SeIncreaseQuotaPrivilege            =   4
SeUnsolicitedInputPrivilege         =   5
SeMachineAccountPrivilege           =   6
SeTcbPrivilege                      =   7
SeSecurityPrivilege                 =   8
SeTakeOwnershipPrivilege            =   9
SeLoadDriverPrivilege               =   10
SeSystemProfilePrivilege            =   11
SeSystemtimePrivilege               =   12
SeProfileSingleProcessPrivilege     =   13
SeIncreaseBasePriorityPrivilege     =   14
SeCreatePagefilePrivilege           =   15
SeCreatePermanentPrivilege          =   16
SeBackupPrivilege                   =   17
SeRestorePrivilege                  =   18
SeShutdownPrivilege                 =   19
SeDebugPrivilege                    =   20
SeAuditPrivilege                    =   21
SeSystemEnvironmentPrivilege        =   22
SeChangeNotifyPrivilege             =   23
SeRemoteShutdownPrivilege           =   24
SeUndockPrivilege                   =   25
SeSyncAgentPrivilege                =   26
SeEnableDelegationPrivilege         =   27
SeManageVolumePrivilege             =   28
SeImpersonatePrivilege              =   29
SeCreateGlobalPrivilege             =   30
SeTrustedCredManAccessPrivilege     =   31
SeRelabelPrivilege                  =   32
SeIncreaseWorkingSetPrivilege       =   33
SeTimeZonePrivilege                 =   34
SeCreateSymbolicLinkPrivilege       =   35

NtShutdownSystem的详细介绍:https://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/Hardware/NtShutdownSystem.html

RtlAdjustPrivilege的详细介绍:http://www.pinvoke.net/default.aspx/ntdll/RtlAdjustPrivilege.html