在给软件添加快捷键时,经常遇到其它软件或者系统已设置的快捷键,导致功能冲突。
HotKey函数下面介绍一个user32.dll的RegisterHotKey以及UnregisterHotKey热键处理的函数
注册热键 RegisterHotKey function
BOOL RegisterHotKey(
HWND hWnd, //响应热键的窗口句柄,如果为空,则注册到调用线程上
Int id, //热键的唯一标识
UINT fsModifiers, //热键的辅助按键
UINT vk //热键的键值
);
解除注册热键 UnregisterHotKey function
BOOL WINAPI UnregisterHotKey(
HWND hWnd,//热键注册的窗口
int id//要解除注册的热键ID
);
流程:
Register方法 - 注册user32.dll函数RegisterHotKey以禁用全局键,并在缓存内添加禁用记录
ProcessHotKey方法 - 外界全局键调用时,调用回调函数
1 public class HotKeys 2 { 3 //引入系统API 4 [DllImport("user32.dll")] 5 static extern bool RegisterHotKey(IntPtr hWnd, int id, int modifiers, Keys vk); 6 [DllImport("user32.dll")] 7 static extern bool UnregisterHotKey(IntPtr hWnd, int id); 8 9 //标识-区分不同的快捷键 10 int keyid = 10; 11 //添加key值注册字典,后续调用时有回调处理函数 12 Dictionary<int, HotKeyCallBackHanlder> keyDict = new Dictionary<int, HotKeyCallBackHanlder>(); 13 public delegate void HotKeyCallBackHanlder(); 14 15 //组合控制键 16 public enum HotkeyModifiers 17 { 18 Alt = 1, 19 Control = 2, 20 Shift = 4, 21 Win = 8 22 } 23 24 //注册快捷键 25 public void Register(IntPtr hWnd, int modifiers, Keys vk, HotKeyCallBackHanlder callBack) 26 { 27 int id = keyid++; 28 if (!RegisterHotKey(hWnd, id, modifiers, vk)) 29 throw new Exception("注册失败!"); 30 keyDict[id] = callBack; 31 } 32 33 // 注销快捷键 34 public void UnRegister(IntPtr hWnd, HotKeyCallBackHanlder callBack) 35 { 36 foreach (KeyValuePair<int, HotKeyCallBackHanlder> var in keyDict) 37 { 38 if (var.Value == callBack) 39 { 40 UnregisterHotKey(hWnd, var.Key); 41 return; 42 } 43 } 44 } 45 46 // 快捷键消息处理 47 public void ProcessHotKey(Message message) 48 { 49 if (message.Msg == 0x312) 50 { 51 int id = message.WParam.ToInt32(); 52 HotKeyCallBackHanlder callback; 53 if (keyDict.TryGetValue(id, out callback)) 54 callback(); 55 } 56 } 57 //快捷键消息处理 58 public void ProcessHotKey(int msg, IntPtr wParam) 59 { 60 if (msg == 0x312) 61 { 62 int id = wParam.ToInt32(); 63 HotKeyCallBackHanlder callback; 64 if (keyDict.TryGetValue(id, out callback)) 65 callback(); 66 } 67 } 68 }