Hello Nijboer,
I modified the code as follow:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace zTestWindowsForms
{
public partial class Form1 : Form
{
internal const UInt32 SE_PRIVILEGE_ENABLED = 0x00000002;
internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020;
internal const int TOKEN_QUERY = 0x8;
internal const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";
[DllImport("Kernel32.dll")]
public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
[MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
ref TOKEN_PRIVILEGES NewState,
UInt32 Zero,
IntPtr Null1,
IntPtr Null2);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool LookupPrivilegeValue(string lpSystemName, string lpName, out LUID lpLuid);
public Form1()
{
InitializeComponent();
GetPrivilege();
}
private static void GetPrivilege()
{
IntPtr processHandle = Process.GetCurrentProcess().Handle;
IntPtr tokenHandle;
if (OpenProcessToken(processHandle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out tokenHandle))
{
LUID luid = new LUID();
LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, out luid);
TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();
tkp.PrivilegeCount = 1;
tkp.Luid = luid;
tkp.Attributes = SE_PRIVILEGE_ENABLED;
bool b = AdjustTokenPrivileges(tokenHandle, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero);
int result = Marshal.GetLastWin32Error();
MessageBox.Show("result = " + result);
}
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == (int)WindowMessage.WM_POWERBROADCAST)
{
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_AWAYMODE_REQUIRED);
MessageBox.Show("Gotcha!!");
Thread.Sleep(10000);
SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS);
}
base.WndProc(ref m);
}
}
internal enum WindowMessage
{
WM_POWERBROADCAST = 0x218,
PBT_APMQUERYSUSPEND = 0x0,
PBT_APMQUERYSTANDBY = 0x0001,
BROADCAST_QUERY_DENY = 0x424D5144,
PBT_APMSUSPEND = 0x4,
}
public enum EXECUTION_STATE : uint
{
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
ES_DISPLAY_REQUIRED = 0x00000002,
ES_SYSTEM_REQUIRED = 0x00000001,
ES_USER_PRESENT = 0x00000004,
}
[StructLayout(LayoutKind.Sequential)]
public struct TOKEN_PRIVILEGES
{
public UInt32 PrivilegeCount;
public LUID Luid;
public UInt32 Attributes;
}
[StructLayout(LayoutKind.Sequential)]
public struct LUID
{
public uint LowPart;
public int HighPart;
}
}
but the result are the same.