Windows API

BlitzMax Forums/BlitzMax Beginners Area/Windows API

Had a go here but I'm getting a failure at OpenProcessToken() call in the EnableShutDown() function.
I'm not sure if GetCurrentProcess() is causing the problem here. I always get -1 as the return value.

See if this works for you:
Strict
Framework BRL.Blitz

' =========================================================================
Extern "Win32"
	Function LoadLibraryA(lib$z)
	Function GetProcAddress:Byte Ptr(lib%,fname$z)
	Function SetSystemPowerState(fSuspend%,fForce%)
	Function ExitWindowsEx(uFlags%,dwReserved%=0)
	Function GetCurrentProcess%()
	Function CloseHandle(hObject%)
End Extern

Global OpenProcessToken%(ProcessHandle%,DesiredAccess%,TokenHandle%) "Win32"
Global LookupPrivilegeValue%(lpSystemName$z,lpName$z,lpLuid:Byte Ptr) "Win32"
Global AdjustTokenPrivileges%(TokenHandle%,DisableAllPrivileges%, NewState:Byte Ptr,BufferLength%,PreviousState:Byte Ptr,ReturnLength%) "Win32"

Local lib%=LoadLibraryA ("advapi32.dll")
If lib
	OpenProcessToken = GetProcAddress(lib, "OpenProcessToken")
	LookupPrivilegeValue = GetProcAddress(lib, "LookupPrivilegeValueA")
	AdjustTokenPrivileges = GetProcAddress(lib, "AdjustTokenPrivileges")
Else
	RuntimeError "Unable to open ADVAPI32.DLL"
EndIf
' =========================================================================


Type LUID
    Field LowPart%
    Field HighPart%
End Type
Type LUID_AND_ATTRIBUTES
    Field pLuid:LUID=New LUID
    Field Attributes%
End Type
Type TOKEN_PRIVILEGES
    Field PrivilegeCount%
    Field Privileges:LUID_AND_ATTRIBUTES=New LUID_AND_ATTRIBUTES
End Type

Const ANYSIZE_ARRAY = $1
Const TOKEN_ADJUST_PRIVILEGES = $20
Const TOKEN_QUERY = $8
Const SE_PRIVILEGE_ENABLED = $2

Const EWX_LOGOFF = 0 
Const EWX_SHUTDOWN = $1 
Const EWX_REBOOT = $2 
Const EWX_FORCE = $4 
Const EWX_POWEROFF = $8 
Const EWX_FORCEIFHUNG = $10 ' NT5 only 
Const EWX_RESET = EWX_LOGOFF | EWX_FORCE | EWX_REBOOT 


' =========================================================================

' Enable shutdown privilege for the current application
Function EnableShutDown()
	Local hToken%
	Local nLuid:LUID=New LUID
	Local mPriv:TOKEN_PRIVILEGES=New TOKEN_PRIVILEGES
	Local mNewPriv:TOKEN_PRIVILEGES=New TOKEN_PRIVILEGES
	DebugLog LookupPrivilegeValue("", "SeShutdownPrivilege", Byte Ptr(nLuid))
	Local hProc% = GetCurrentProcess()
	DebugLog hproc
	DebugLog OpenProcessToken(hProc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, hToken)
	DebugLog hToken
	mPriv.PrivilegeCount = 1
	mPriv.Privileges.pLuid.LowPart = nLuid.LowPart
	mPriv.Privileges.pLuid.HighPart = nLuid.HighPart
	mPriv.Privileges.Attributes = SE_PRIVILEGE_ENABLED
	DebugLog AdjustTokenPrivileges(hToken, 0, Byte Ptr(mNewPriv), SizeOf mNewPriv, Byte Ptr(mPriv), SizeOf mPriv)
	'CloseHandle hToken ' not needed for pseudo handles
End Function

' =========================================================================

' TEST

EnableShutDown
SetSystemPowerState False, False
'ExitWindowsEx EWX_POWEROFF