Search code examples
c#.nethotkeys

Using Global Hotkeys: Get key that was actually pressed


In my form, I register different Hotkeys. Later during execution, I would like to know which of the Hotkeys was actually pressed. Where can I get that information from?

Registering during Initialization:

public Form1()
{
   this.KeyPreview = true;
   ghk = new KeyHandler(Keys.F1, this);
   ghk.Register();
   ghk = new KeyHandler(Keys.F2, this);
   ghk.Register();
   InitializeComponent();
}

Using this KeyHandler Class:

public class KeyHandler
{
    [DllImport("user32.dll")]
    private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);

    [DllImport("user32.dll")]
    private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    private int key;
    private IntPtr hWnd;
    private int id;

    public KeyHandler(Keys key, Form form)
    {
        this.key = (int)key;
        this.hWnd = form.Handle;
        id = this.GetHashCode();
    }

    public override int GetHashCode()
    {
        return key ^ hWnd.ToInt32();
    }

    public bool Register()
    {
        return RegisterHotKey(hWnd, id, 0, key);
    }

    public bool Unregister()
    {
        return UnregisterHotKey(hWnd, id);
    }
}

The method that is triggered:

protected override void WndProc(ref Message m)
{
   if (m.Msg == Constants.WmHotkeyMsgId)
   HandleHotkey(m);
   base.WndProc(ref m);
}

Here I want to distinguish between two Hotkeys:

private void HandleHotkey(Message m)
{
   if(key == F1)
      DoSomething
   if(key == F2)
      DoSomethingElse
}

Solution

  • You should be able to know the actual key by using the id. When you register the hotkey, you use an id, a key and a modifier. When the hotkey is pressed, Windows gives you the id of the hotkey in the callback, not the key and modifiers.

    RegisterHotKey(Handle, id: 1, ModifierKeys.Control, Keys.A);
    RegisterHotKey(Handle, id: 2, ModifierKeys.Control | ModifierKeys.Alt, Keys.B);
    
    const int WmHotKey = 786;
    if (msg.message != WmHotKey)
        return;
    
    var id = (int)msg.wParam;
    if (id == 1) // Ctrl + A
    {
    }
    else if (id == 2) // Ctrl + Alt + B
    {
    }
    

    Here's a blog post I've written with the code to register a hotkey for a WPF application: https://www.meziantou.net/2012/06/28/hotkey-global-shortcuts