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