private static void AdjustTokenPrivilegesForShutdown()
{
IntPtr procHandle = System.Diagnostics.Process.GetCurrentProcess().Handle;
IntPtr tokenHandle = IntPtr.Zero;
bool tokenOpenResult = OpenProcessToken(procHandle, TOKENADJUSTPRIVILEGES | TOKENQUERY, out tokenHandle);
if (!tokenOpenResult)
{
throw new ApplicationException("Error attempting to open process token to raise level for shutdown.\nWin32 Error Code: " + Marshal.GetLastWin32Error());
}
long pluid = new long();
bool privLookupResult = LookupPrivilegeValue(null, "SeShutdownPrivilege", ref pluid);
if (!privLookupResult)
{
throw new ApplicationException("Error attempting to lookup value for shutdown privilege.\n Win32 Error Code: " + Marshal.GetLastWin32Error());
}
TOKEN_PRIVILEGES newPriv = new TOKEN_PRIVILEGES();
newPriv.Luid = pluid;
newPriv.PrivilegeCount = 1;
newPriv.Attributes = 0x00000002;
bool tokenPrivResult = AdjustTokenPrivileges(tokenHandle, false, ref newPriv, 0, IntPtr.Zero, IntPtr.Zero);
if (!tokenPrivResult)
{
throw new ApplicationException("Error attempting to adjust the token privileges to allow shutdown.\n Win32 Error Code: " + Marshal.GetLastWin32Error());
}
}