我已经实现了user32.dll的注册和注销的热键方法,但是在注册热键之后,按热键时,我再也没有收到WndProc
消息0x0312
。有人可以查看我的代码并帮助我理解为什么我从没收到0x0312
消息的原因。
到目前为止我尝试过的热键组合:
我的实现只是最常见的实现:
[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);
答案 0 :(得分:0)
我想花点时间回答我自己的问题,以防别人发现自己处在同样的状况中。.
因此,在进行了一些探索和探索之后,我终于发现了问题所在,我正在查看传递给RegisterHotKey方法的Key ID的值,并注意到我得到的值与该ID的实际ID不匹配。钥匙。
事实证明,存在两种类型的Key枚举,即System.Windows.Input.Key
和System.Windows.Forms.Keys
。我不知道这一点,因此使用的Input.Key
与Forms.Keys
TL:DR
将Forms.Keys
用于RegisterHotKey()
,而不是Input.Key