首页 > 其他 > 详细

全局监控热键

时间:2014-03-03 15:57:44      阅读:465      评论:0      收藏:0      [点我收藏+]

1.  在类内部声明两个API函数

bubuko.com,布布扣
        [DllImport("user32.dll")]  //在类内部声明两个API函数
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, Keys keys);

        [DllImport("user32.dll")] //在类内部声明两个API函数
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);

       public static int WmHotkey = 0x0312;  //标示用户按下了热键 
bubuko.com,布布扣


2. 系统启动时注册基本事件

bubuko.com,布布扣
        //系统启动时注册基本事件
        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);
            IntPtr hWnd = new WindowInteropHelper(this).Handle; 
            RegisterHotKey(hWnd, 123, 0, Keys.F);   //注册热键
              var source = PresentationSource.FromVisual(this) as HwndSource; //获取内容
              if (source != null) source.AddHook(WndProc);  //注册处理方法
        }
bubuko.com,布布扣

 

3. 编写获取热键时处理方法

bubuko.com,布布扣
        //热键处理  重写WndProc()方法,通过监视系统消息,来调用过程
        private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg != WmHotkey) return IntPtr.Zero;
            if (wParam.ToInt32() == 123)
            {
                ButtonBase_OnClick(null, null);
                handled=true;
            }
            return IntPtr.Zero;
        }
bubuko.com,布布扣

 

4. 系统关闭时注销热键

bubuko.com,布布扣
        //软件关闭时注销热键
        void Window1_Closed(object sender, EventArgs e)
        {
            IntPtr hWnd = new WindowInteropHelper(this).Handle;  
            UnregisterHotKey(hWnd, 123);
        }
bubuko.com,布布扣

 

 

注:

组合键注释:

None = 0, 
Alt = 1, 
Control = 2, 
Shift = 4, 
Windows = 8 

 

 

注册方法参数说明:

hwnd: handle to window
id: hot key identifier          热键标示
control: key-modifier options        用于接收组合键
keys: virtual-key code           热键

全局监控热键,布布扣,bubuko.com

全局监控热键

原文:http://www.cnblogs.com/Alf7/p/3577058.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!