I am developing an application which able shutdown or restart windows. As what I've googled, There are four steps:
- call OpenProcessToken(...)
- check LookupPrivilegeValue(...)
- call AdjustTokenPrivileges(...)
- call ExitWindowsEx(1, 0).
What happened is that until step 3, AdjustTokenPrivileges, all are fine. AdjustTokenPrivileges has set SE_SHUTDOWN_PRIVILEGE, then returns true and err.LastDllError is ERROR_SUCCESS (&h0). But when I call ExitWindowsEx to shutdown windows, it returns 0 and
err.LastDllError is 5. Using errlook command in Visual Studio command prompt, the number 5 means "Access Denied".
I usually work with standard user account (not admin). Later I tried to change requested execution level in app.manifest like this:
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
and then re-run the application as administrator. But no use, I'm still getting LastDllError = 5, access denied.
I am using Windows 7 64-bit with Visual Studio 2010 and .NET framework 4 installed. But for this application I target .NET 3.5 as most my friends have not ready yet for .NET 4. Also the result is the same regardless I compile it to x64 or x86.
Here is my problematic code:
Dim tp As Token_Privileges
Dim processhandle As IntPtr = GetCurrentProcess()
Dim tokenhandle As IntPtr = IntPtr.Zero
'Dim retlength As Integer
OpenProcessToken(processhandle, TOKEN_ADJUST_PRIVILEGES Or TOKEN_QUERY, tokenhandle)
tp.Count = 1
tp.Luid = 0
tp.Attr = SE_PRIVILEGE_ENABLED
'Check whether privilege exists or not
If Not LookupPrivilegeValue(vbNullString, SE_SHUTDOWN_NAME, tp.Luid) Then
MessageBox.Show("LookupPrivilegeValue returns false")
End If
Err.Clear()
'set shutdown privilege
If Not AdjustTokenPrivileges(tokenhandle, False, tp, 0, IntPtr.Zero, IntPtr.Zero) Then
MessageBox.Show(Err.LastDllError) 'this message box never executed,
'which mean AdjustToken successful
End If
If Not ExitWindowsEx(1, 0) Then
MessageBox.Show(Err.LastDllError) 'this always shows "5"
End If
I have read many MSDN blogs and googling here and there, wasting a day, but still getting access denied.
Another thing what I am wondering is why his code in C# works but mine does not? (He even didn't bother to mess with privileges and tokens..)
Oh, I couldn't find a suitable forum title for programming or development in MS answer's new thread page. Moderators, feel free to move this thread into appropriate forum.
Thanks.