在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
int keyid = 10; Dictionary<int, HotKeyCallBackHanlder> keymap = new Dictionary<int, HotKeyCallBackHanlder>(); public delegate void HotKeyCallBackHanlder(); public enum HotkeyModifiers { Alt = 1, Control = 2, Shift = 4, Win = 8 } [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool RegisterHotKey(IntPtr hWnd, int id, int modifiers, System.Windows.Forms.Keys vk); [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool UnregisterHotKey(IntPtr hWnd, int id); /// <summary> /// 注册快捷键 /// </summary> /// <param name="hWnd">持有快捷键窗口的句柄</param> /// <param name="modifiers">组合键</param> /// <param name="vk">快捷键的虚拟键码</param> /// <param name="callBack">回调函数(按下快捷键时被调用的方法)</param> public void Regist(IntPtr hWnd, int modifiers, System.Windows.Forms.Keys vk, HotKeyCallBackHanlder callBack) { int id = keyid++; if (!RegisterHotKey(hWnd, id, modifiers, vk)) throw new Exception("注册失败!"); keymap[id] = callBack; } /// <summary> /// 注销快捷键 /// </summary> /// <param name="hWnd">持有快捷键窗口的句柄</param> /// <param name="callBack">回调函数</param> public void UnRegist(IntPtr hWnd, HotKeyCallBackHanlder callBack) { foreach (KeyValuePair<int, HotKeyCallBackHanlder> var in keymap) { if (var.Value == callBack) UnregisterHotKey(hWnd, var.Key); } } /// <summary> /// 快捷键消息处理 /// </summary> public void ProcessHotKey(System.Windows.Forms.Message m) { if (m.Msg == 0x312) { int id = m.WParam.ToInt32(); HotKeyCallBackHanlder callback; if (keymap.TryGetValue(id, out callback)) callback(); } } 1 HotKeys hotKsys = new HotKeys(); 2 3 private void Form1_Load(object sender, EventArgs e) 4 { 5 hotKsys.Regist(this.Handle, (int)HotKeys.HotkeyModifiers.Control + (int)HotKeys.HotkeyModifiers.Alt, Keys.H, CallBack_Hide);//Ctrl+Alt+H 6 hotKsys.Regist(this.Handle, (int)HotKeys.HotkeyModifiers.Control, Keys.W, CallBack_Show);//Ctrl+W 7 } 8 9 void CallBack_Hide() 10 { 11 this.Hide(); 12 } 13 14 void CallBack_Show() 15 { 16 this.Show(); 17 } 18 19 protected override void WndProc(ref Message m) 20 { 21 hotKsys.ProcessHotKey(m); 22 base.WndProc(ref m); 23 } 24 25 private void Form1_FormClosing(object sender, FormClosingEventArgs e) 26 { 27 hotKsys.UnRegist(this.Handle, CallBack_Hide); 28 hotKsys.UnRegist(this.Handle, CallBack_Show); 29 }
|
请发表评论