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

时间:2019-01-18 03:19:52

标签: c# .net hotkeys

在我的form中,我注册了不同的热键。在执行的后期,我想知道实际按下了哪个热键。我从哪里可以得到这些信息?

初始化期间注册:

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

使用此KeyHandler类:

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
}

1 个答案:

答案 0 :(得分:1)

您应该能够使用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
{
}

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