Public Class Shutdown
<StructLayout(LayoutKind.Sequential, Pack:=1)> _
Friend Structure TokPriv1Luid
Public Count As Integer
Public Luid As Long
Public Attr As Integer
End Structure
<DllImport("kernel32.dll", ExactSpelling:=True)> _
Friend Shared Function GetCurrentProcess() As IntPtr
End Function
<DllImport("advapi32.dll", ExactSpelling:=True, SetLastError:=True)> _
Friend Shared Function OpenProcessToken(ByVal h As IntPtr, ByVal acc As Integer, ByRef phtok As IntPtr) As Boolean
End Function
<DllImport("advapi32.dll", SetLastError:=True)> _
Friend Shared Function LookupPrivilegeValue(ByVal host As String, ByVal name As String, ByRef pluid As Long) As Boolean
End Function
<DllImport("advapi32.dll", ExactSpelling:=True, SetLastError:=True)> _
Friend Shared Function AdjustTokenPrivileges(ByVal htok As IntPtr, ByVal disall As Boolean, ByRef newst As TokPriv1Luid, ByVal len As Integer, ByVal prev As IntPtr, ByVal relen As IntPtr) As Boolean
End Function
<DllImport("user32.dll", ExactSpelling:=True, SetLastError:=True)> _
Friend Shared Function ExitWindowsEx(ByVal DoFlag As Integer, ByVal rea As Integer) As Boolean
End Function
Friend Const SE_PRIVILEGE_ENABLED As Integer = &H00000002
Friend Const TOKEN_QUERY As Integer = &H00000008
Friend Const TOKEN_ADJUST_PRIVILEGES As Integer = &H00000020
Friend Const SE_SHUTDOWN_NAME As String = "SeShutdownPrivilege"
Friend Const EWX_LOGOFF As Integer = &H00000000
Friend Const EWX_SHUTDOWN As Integer = &H00000001
Friend Const EWX_REBOOT As Integer = &H00000002
Friend Const EWX_FORCE As Integer = &H00000004
Friend Const EWX_POWEROFF As Integer = &H00000008
Friend Const EWX_FORCEIFHUNG As Integer = &H00000010
Private Shared Sub DoExitWin(ByVal DoFlag As Integer)
Dim ok As Boolean
Dim tp As TokPriv1Luid
Dim hproc As IntPtr = GetCurrentProcess()
Dim htok As IntPtr = IntPtr.Zero
ok = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, htok)
tp.Count = 1
tp.Luid = 0
tp.Attr = SE_PRIVILEGE_ENABLED
ok = LookupPrivilegeValue(Nothing, SE_SHUTDOWN_NAME, tp.Luid)
ok = AdjustTokenPrivileges(htok, False, tp, 0, IntPtr.Zero, IntPtr.Zero)
ok = ExitWindowsEx(DoFlag, 0)
End Sub
Public Shared Sub Reboot()
DoExitWin(EWX_FORCE Or EWX_REBOOT)
End Sub
Public Shared Sub PowerOff()
DoExitWin(EWX_FORCE Or EWX_POWEROFF)
End Sub
Public Shared Sub LogOff()
DoExitWin(EWX_FORCE Or EWX_LOGOFF)
End Sub
End Class
------------------
调用,如
shutdown.LogOff()