繁体   English   中英

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

[英]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类:

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

这是我写的一篇博客文章,其中包含为WPF应用程序注册热键的代码: https//www.meziantou.net/2012/06/28/hotkey-global-shortcuts

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM