/// <summary>
/// Adjusts the current process's token privileges to allow it to shut down or reboot the machine.
/// Throws an ApplicationException if an error is encountered.
/// </summary>
private static void AdjustTokenPrivilegesForShutdown()
{
IntPtr procHandle = System.Diagnostics.Process.GetCurrentProcess().Handle;
IntPtr tokenHandle = IntPtr.Zero;
bool tokenOpenResult = NativeMethods.OpenProcessToken(procHandle, NativeMethods.TOKENADJUSTPRIVILEGES | NativeMethods.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 = NativeMethods.LookupPrivilegeValue(null, "SeShutdownPrivilege", ref pluid);
if (!privLookupResult)
{
throw new ApplicationException("Error attempting to lookup value for shutdown privilege.\n Win32 Error Code: " + Marshal.GetLastWin32Error());
}
NativeMethods.TOKEN_PRIVILEGES newPriv = new NativeMethods.TOKEN_PRIVILEGES();
newPriv.Luid = pluid;
newPriv.PrivilegeCount = 1;
newPriv.Attributes = 0x00000002;
bool tokenPrivResult = NativeMethods.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());
}
}