为什么按热键组合时未触发我的注册热键

时间:2020-01-31 09:14:23

标签: c# user32 registerhotkey

我已经实现了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);

1 个答案:

答案 0 :(得分:0)

我想花点时间回答我自己的问题,以防别人发现自己处在同样的状况中。.

因此,在进行了一些探索和探索之后,我终于发现了问题所在,我正在查看传递给RegisterHotKey方法的Key ID的值,并注意到我得到的值与该ID的实际ID不匹配。钥匙。
事实证明,存在两种类型的Key枚举,即System.Windows.Input.KeySystem.Windows.Forms.Keys。我不知道这一点,因此使用的Input.KeyForms.Keys

具有不同的值

TL:DR
Forms.Keys用于RegisterHotKey(),而不是Input.Key