/// <summary> The RegisterHotKey function defines a system-wide hot key </summary>
/// <param name="hWnd">Handle to the window that will receive WM_HOTKEY messages
/// generated by the hot key.</param>
/// <param name="id">Specifies the identifier of the hot key.</param>
/// <param name="fsModifiers">Specifies keys that must be pressed in combination with the key
/// specified by the 'virtualKey' parameter in order to generate the WM_HOTKEY message.</param>
/// <param name="virtualKey">Specifies the virtual-key code of the hot key</param>
/// <returns><c>true</c> if the function succeeds, otherwise <c>false</c></returns>
/// <seealso cref="http://msdn.microsoft.com/en-us/library/ms646309(VS.85).aspx"/>
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint virtualKey);
[DllImport("user32.dll")]
private static extern bool UnregisterHotKey(IntPtr hWnd, int id);
public static int MOD_CONTROL = 0x2;
public static int MOD_SHIFT = 0x4;
public static int WM_HOTKEY = 0x312;
private static int keyId;
public static void RegisterHotKey(Form f, Keys key)
{
int modifiers = 0;
if ((key & Keys.Control) == Keys.Control)
modifiers = modifiers | MOD_CONTROL;
if ((key & Keys.Shift) == Keys.Shift)
modifiers = modifiers | MOD_SHIFT;
Keys k = key & ~Keys.Control & ~Keys.Shift;
Func<bool> ff = () =>
{
keyId = f.GetHashCode();
RegisterHotKey(f.Handle, keyId, (uint) modifiers, (uint) k);
return true;
};
if (f.InvokeRequired)
f.Invoke(ff);
else
ff();
}
public static void UnregisterHotKey(Form f)
{
try
{
Func<bool> ff = () =>
{
UnregisterHotKey(f.Handle, keyId);
return true;
};
if (f.InvokeRequired)
f.Invoke(ff);
else
ff();
}
catch (Exception ex)
{
Debug.WriteLine(ex.ToString());
}
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == WM_HOTKEY)
throw new Exception("You found an Easter Egg.");
}