Created
August 10, 2012 02:34
-
-
Save dck-jp/3310469 to your computer and use it in GitHub Desktop.
Shutdown Windows @ VBA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Option Explicit | |
Private Const SE_SHUTDOWN_NAME = "SeShutdownPrivilege" | |
Private Const SE_PRIVILEGE_ENABLED = &H2 | |
Private Const ANYSIZE_ARRAY = 1 | |
Private Const TOKEN_ALL_ACCESS = &HF00FF | |
Private Type LUID | |
LowPart As Long | |
HighPart As Long | |
End Type | |
Private Type LUID_AND_ATTRIBUTES | |
pLuid As LUID | |
Attributes As Long | |
End Type | |
Private Type TOKEN_PRIVILEGES | |
PrivilegeCount As Long | |
Privileges(ANYSIZE_ARRAY) As LUID_AND_ATTRIBUTES | |
End Type | |
Private Declare Function ExitWindowsEx Lib "user32" (ByVal uFlags As Long, _ | |
ByVal dwReserved As Long) As Long | |
Private Declare Function GetCurrentProcess Lib "kernel32" () As Long | |
Private Declare Function OpenProcessToken Lib "advapi32.dll" (ByVal ProcessHandle As Long, _ | |
ByVal DesiredAccess As Long, TokenHandle As Long) As Long | |
Private Declare Function LookupPrivilegeValue Lib "advapi32.dll" Alias "LookupPrivilegeValueA" _ | |
(ByVal lpSystemName As Long, _ | |
ByVal lpName As String, lpLuid As LUID) As Long | |
Private Declare Function AdjustTokenPrivileges Lib "advapi32.dll" (ByVal TokenHandle As Long, _ | |
ByVal DisableAllPrivileges As Long, NewState As TOKEN_PRIVILEGES, _ | |
ByVal BufferLength As Long, ByVal PreviousState As Long, _ | |
ByVal ReturnLength As Long) As Long | |
'lngSDFlg: | |
' 0: logoff | |
' 1: shutdown | |
' 2: reboot | |
Public Sub ShutDown(lngSDFlg As Long) | |
Dim lngToken As Long | |
Dim udtTokenPrv As TOKEN_PRIVILEGES | |
Dim lngRet As Long | |
lngRet = OpenProcessToken(GetCurrentProcess(), TOKEN_ALL_ACCESS, lngToken) | |
lngRet = LookupPrivilegeValue(0, SE_SHUTDOWN_NAME, udtTokenPrv.Privileges(0).pLuid) | |
With udtTokenPrv | |
.PrivilegeCount = 1 | |
.Privileges(0).Attributes = SE_PRIVILEGE_ENABLED | |
End With | |
lngRet = AdjustTokenPrivileges(lngToken, 0, udtTokenPrv, 0, 0, 0) | |
ExitWindowsEx lngSDFlg, 0 | |
End Sub |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment