public HotKey(Window win, HotKey.KeyFlags control, System.Windows.Forms.Keys key) //构造函数,注册热键 { Handle = new WindowInteropHelper(win).Handle; window = win; Controlkey = (uint)control; Key = (uint)key; KeyId = num++; if (HotKey.KeyPair.ContainsKey(KeyId)) { IRightRegistered = false; MessageBox.Show("热键已经被注册!"); return; } //注册热键 if (false == HotKey.RegisterHotKey(Handle, KeyId, Controlkey, Key)) { IRightRegistered = false; MessageBox.Show("热键注册失败!"); return; } if (HotKey.KeyPair.Count == 0) { //消息挂钩只能连接一次!! if (false == InstallHotKeyHook(this)) //创建 { IRightRegistered = false; MessageBox.Show("消息挂钩连接失败!"); return; } } //添加这个热键索引 HotKey.KeyPair.Add(KeyId, this); }
//热键注册 public static void RegisterHotKey(HotKey.KeyFlags control, System.Windows.Forms.Keys key) { hotKey = new HotKey(Application.Current.MainWindow, control, key); hotKey.OnHotKey += new HotKey.OnHotkeyEventHandeler(hotKey_OnHotKey); }
static private bool InstallHotKeyHook(HotKey hk) //安装热键处理挂钩 { if (hk.window == null || hk.Handle == IntPtr.Zero) return false; //获得消息源 System.Windows.Interop.HwndSource source = System.Windows.Interop.HwndSource.FromHwnd(hk.Handle); if (source == null) return false; //挂接事件 source.AddHook(HotKey.HotKeyHook); return true; }
public void IUnregisterHotKey() { HotKey.UnregisterHotKey(Handle, KeyId); }