I am trying shut down work stations that are left on over night. This
works great when a user is logged in or the machine is locked but fails
miserably when no body is using the work
station, the programme starts but does not execute. The program below
runs ok right down to shut down call then fails,
any help will be gratefully received
Imports System
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
Shutdown()
End Sub
' Constants
Const SE_PRIVILEGE_ENABLED As Integer = &H2
Const TOKEN_QUERY As Integer = &H8
Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
Const SE_SHUTDOWN_NAME As String = "SeShutdownPrivilege"
' Exit Windows Constants
Const EWX_LOGOFF As Integer = &H0
Const EWX_SHUTDOWN As Integer = &H1
Const EWX_REBOOT As Integer = &H2
Const EWX_FORCE As Integer = &H4
Const EWX_POWEROFF As Integer = &H8
Const EWX_FORCEIFHUNG As Integer = &H10
'Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)_
Friend Structure Luid
Public Count As Integer
Public Luid As Long
Public Attr As Integer
End Structure 'TokPriv1Luid
' Lock Workstation
<DllImport("user32.dll", ExactSpelling:=True)_
Function LockWorkStation() As Boolean
End Function
' Get Current Processes
<DllImport("kernel32.dll", ExactSpelling:=True)_
Function GetCurrentProcess() As IntPtr
End Function
' Open Process Token
<DllImport("advapi32.dll", SetLastError:=True)_
Function OpenProcessToken(ByVal h As IntPtr, ByVal acc As Integer,
ByRef phtok As IntPtr) As Boolean
End Function
' Look up Priviledge Value
<DllImport("advapi32.dll", SetLastError:=True)_
Friend Function LookupPrivilegeValue(ByVal host As String, ByVal
name As String, ByRef pluid As Long) As Boolean
End Function
' Adjust Token Priviledges
<DllImport("advapi32.dll", ExactSpelling:=True,
SetLastError:=True)_
Friend Function AdjustTokenPrivileges(ByVal htok As IntPtr, ByVal
disall As Boolean, ByRef newst As Luid, ByVal len As Integer, ByVal
prev As IntPtr, ByVal relen As IntPtr) As Boolean
End Function
' Exit Windows
<DllImport("user32.dll", ExactSpelling:=True, SetLastError:=True)>
_
Friend Function ExitWindowsEx(ByVal flg As Integer, ByVal rea As
Integer) As Boolean
End Function
' Exit Windows Sub
Private Sub DoExitWindows(ByVal flg As Integer)
Dim tp As Luid
Dim hproc As IntPtr = GetCurrentProcess()
Dim htok As IntPtr = IntPtr.Zero
OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY,
htok)
tp.Count = 1
tp.Luid = 0
tp.Attr = SE_PRIVILEGE_ENABLED
LookupPrivilegeValue(Nothing, SE_SHUTDOWN_NAME, tp.Luid)
AdjustTokenPrivileges(htok, False, tp, 0, IntPtr.Zero,
IntPtr.Zero)
ExitWindowsEx(flg, 0)
End Sub
' Shutdown
Public Sub Shutdown()
DoExitWindows(EWX_SHUTDOWN Or EWX_FORCE)
End Sub
' Restart
Public Sub Restart()
DoExitWindows(EWX_REBOOT Or EWX_FORCE)
End Sub
' Log off
Public Sub LogOff()
DoExitWindows(EWX_LOGOFF)
End Sub
' Lock Workstation
Public Sub LockTheComputer()
LockWorkStation()
End Sub
End Module