Beispiel #1
0
        Window window; //热键所在窗体

        #endregion Fields

        #region Constructors

        //构造函数,注册热键
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="win">注册窗体</param>
        /// <param name="control">控制键</param>
        /// <param name="key">主键</param>
        public HotKey(Window win, HotKey.KeyFlags control, Keys key)
        {
            Handle = new WindowInteropHelper(win).Handle;
            window=win;
            Controlkey = (uint)control;
            Key = (uint)key;
            KeyId=(int)Controlkey+(int)Key*10;
            if (HotKey.KeyPair.ContainsKey(KeyId))
            {
                throw new Exception("热键已经被注册!");
            }

            //注册热键
            if(false == HotKey.RegisterHotKey(Handle, KeyId, Controlkey, Key))
            {
                throw new Exception("热键注册失败!");
            }
            if(HotKey.KeyPair.Count==0){
                //消息挂钩只能连接一次!!
                if(false == InstallHotKeyHook(this))
                {
                    throw new Exception("消息挂钩连接失败!");
                }
            }

            //添加这个热键索引
            HotKey.KeyPair.Add(KeyId, this);
        }
Beispiel #2
0
        //安装热键处理挂钩
        private static 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;
        }