1

我已经实现了 user32.dll 注册和取消注册热键方法,但是在注册热键后,按下热键时我永远不会收到WndProc消息。0x0312有人可以查看我的代码并帮助我理解为什么我从未收到该0x0312消息。

到目前为止我尝试过的热键组合:

  • Ctrl + Shift + F12
  • F12
  • F9

我的实现只是最常见的实现:

[DllImport("c:\\windows\\system32\\user32.dll")]
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
[DllImport("c:\\windows\\system32\\user32.dll")]
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
protected override void WndProc(ref Message m) {
    if(m.Msg == 0x0312) {
        int id = m.WParam.ToInt32();
        switch(id) {
            case 0:
                MessageBox.Show("Ctrl + Shift + F12 HotKey Pressed ! Do something here ... ");
                break;
        }
    }
}

我创建了一个单例类来处理热键的注册和注销:

public class HotKeyHandler {

    //Hotkey register and unregister.
    [DllImport("c:\\windows\\system32\\user32.dll")]
    public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
    [DllImport("c:\\windows\\system32\\user32.dll")]
    public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

    public const int MOD_ALT = 0x0001;
    public const int MOD_CONTROL = 0x0002;
    public const int MOD_SHIFT = 0x0004;
    public const int MOD_WIN = 0x0008;

    byte ID = 0;

    /// <summary>
    /// Keep the constructor private due to singleton implementation
    /// </summary>
    private HotKeyHandler() { }
    public static HotKeyHandler Instance = new HotKeyHandler();

    public bool RegisterHotKey(IntPtr handle, int modifier, Key key) {
        bool returnVal = RegisterHotKey(handle, ID, modifier, (int) key);
        ID++;
        return returnVal;
    }

    public void UnregisterAllHotKeys(IntPtr handle) {
        for(short s = 0; s <= ID; s++) {
            UnregisterHotKey(handle, s);
        }
    }
}

最后我像这样注册热键:

HotKeyHandler.Instance.RegisterHotKey(this.Handle, HotKeyHandler.MOD_CONTROL | HotKeyHandler.MOD_SHIFT, Key.F12);
4

1 回答 1

0

我想花时间回答我自己的问题,以防其他人可能会发现自己处于同样的境地......相当恼人的情况......

因此,经过一番挖掘和刺激,我终于发现了问题所在,我查看了传递给 RegisterHotKey 方法的 Key ID 的值,并注意到我得到的值与 Key 的实际 ID 不匹配。
原来存在两种类型的 Key 枚举,有System.Windows.Input.KeySystem.Windows.Forms.Keys。我没有意识到这一点,并且正在使用Input.KeyForms.Keys

TL:DR
用于Forms.KeysRegisterHotKey()不是Input.Key

于 2020-02-03T09:46:37.740 回答