使用全局热键:获取实际按下的键

Using Global Hotkeys: Get key that was actually pressed

在我的 form 中,我注册了不同的热键。后来在执行过程中,我想知道实际上按下了哪个热键。我可以从哪里获取该信息?

正在初始化期间注册:

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

使用这个 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);
    }
}

触发的方法:

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

这里我要区分两个热键:

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

你应该可以通过id知道真正的密钥。当您注册热键时,您会使用一个 ID、一个键和一个修饰符。按下热键时,Windows 会在回调中为您提供热键的 ID,而不是按键和修饰符。

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
{
}

这是一篇博客 post 我编写了用于为 WPF 应用程序注册热键的代码: https://www.meziantou.net/2012/06/28/hotkey-global-shortcuts