I have a C# Winforms system tray application which is supposed to put all my monitors to sleep when the icon clicked or on a keyboard screenshot.
To send the monitors to sleep I use this code
private int SC_MONITORPOWER = 0xF170;
private uint WM_SYSCOMMAND = 0x0112;
//For sleeping monitors
[DllImport("user32.dll")]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
private void SchnozOff()
{
SendMessage(this.Handle, WM_SYSCOMMAND, (IntPtr)SC_MONITORPOWER, (IntPtr)2);
}
This code works fine when called from a MouseClick event handler
private void sysTrayIcon_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
SchnozOff();
} else if (e.Button == MouseButtons.Middle)
{
Application.Exit();
}
}
However I also have it called on a keyboard shortcut (Ctrl + Alt + S). When I do this the monitors go to sleep but then immediately wake up again, even though I haven't touched the keyboard/mouse (the intended action to wake the monitors).
// DLL libraries used to manage hotkeys
[DllImport("user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
private const int MYACTION_HOTKEY_ID = 1;
private void RegisterHotkeys()
{
// Modifier keys codes: Alt = 1, Ctrl = 2, Shift = 4, Win = 8
// Compute the addition of each combination of the keys you want to be pressed
// ALT+CTRL = 1 + 2 = 3 , CTRL+SHIFT = 2 + 4 = 6...
int Ctrl = 1;
int Alt = 2;
RegisterHotKey(this.Handle, MYACTION_HOTKEY_ID, Ctrl + Alt, (int)Keys.S);
}
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0312 && m.WParam.ToInt32() == MYACTION_HOTKEY_ID)
{
SchnozOff();
}
base.WndProc(ref m);
}
The rest of the code is here if it's helpful. I can assure you there isn't much more to see really though.