'==============================
' 关机与提高进程权限 声明
'============================
Public Enum HowExitConst
EWX_FORCE = 4 ' 强制关机
EWX_LOGOFF = 0 ' 注销
EWX_REBOOT = 2 ' 重起
EWX_SHUTDOWN = 1 ' 关机
End Enum
Const TOKEN_ADJUST_PRIVILEGES = &H20
Const TOKEN_QUERY = &H8
Const SE_PRIVILEGE_ENABLED = &H2
Const ANYSIZE_ARRAY = 1
Public Type LUID
lowpart As Long
highpart As Long
End Type
Public Type LUID_AND_ATTRIBUTES
pLuid As LUID
Attributes As Long
End Type
Public Type TOKEN_PRIVILEGES
PrivilegeCount As Long
Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES
End Type
Public Declare Function ExitWindowsEx Lib "user32" ( _
ByVal uFlags As Long, _
ByVal dwReserved As Long) As Long '关机声明
Public Declare Function GetCurrentProcess Lib "kernel32" () As Long
Public Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" ( _
ByVal lpSystemName As String, _
ByVal lpName As String, _
lpLuid As LUID) _
As Long
Public Declare Function AdjustTokenPrivileges Lib "advapi32.dll" _
(ByVal TokenHandle As Long, _
ByVal DisableAllPrivileges As Long, _
NewState As TOKEN_PRIVILEGES, _
ByVal BufferLength As Long, _
PreviousState As TOKEN_PRIVILEGES, _
ReturnLength As Long) _
As Long
Public Declare Function OpenProcessToken Lib "advapi32.dll" _
(ByVal ProcessHandle As Long, _
ByVal DesiredAccess As Long, _
TokenHandle As Long) As Long
'==============================
' 当前进程权限的提高
'==============================
Public Sub AdjustToken()
Dim hdlProcessHandle As Long
Dim hdlTokenHandle As Long
Dim tmpLuid As LUID
Dim tkp As TOKEN_PRIVILEGES
Dim tkpNewButIgnored As TOKEN_PRIVILEGES
Dim lBufferNeeded As Long
hdlProcessHandle = GetCurrentProcess() '获取当前进程ID
OpenProcessToken hdlProcessHandle, (TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY), _
hdlTokenHandle
LookupPrivilegeValue "", "SeShutdownPrivilege", tmpLuid
tkp.PrivilegeCount = 1
tkp.Privileges(0).pLuid = tmpLuid
tkp.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED
'权限的提高
AdjustTokenPrivileges hdlTokenHandle, False, tkp, Len(tkpNewButIgnored), _
tkpNewButIgnored, lBufferNeeded
End Sub
'=============================
' 关机操作
'=============================
Public Sub shutWindows()
Call AdjustToken
Call ExitWindowsEx(EWX_SHUTDOWN Or EWX_FORCE, 0)
End Sub
'=============================
' 注销操作
'=============================
Public Sub LogOffWindows()
Call AdjustToken
Call ExitWindowsEx(EWX_LOGOFF, 0)
End Sub
'=============================
' 重起操作
'=============================
Public Sub ReBootWindows()
Call AdjustToken
Call ExitWindowsEx(EWX_REBOOT, 0)
End Sub