【转】获取其他程序的按键消息,利用钩子函数

      
using System.Runtime.InteropServices;

        /// <summary>
        /// Register HotKeys
        /// </summary>
        /// <param name="hWnd">handle to window</param>
        /// <param name="id">hot key identifier</param>
        /// <param name="fsModifiers">key-modifier options</param>
        /// <param name="vk">virtual-key code</param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, KeyModifiers fsModifiers, Keys vk);

        /// <summary>
        /// UnRegister HotKeys
        /// </summary>
        /// <param name="hWnd">handle to window</param>
        /// <param name="id">hot key identifier</param>
        /// <returns></returns>
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnRegisterHotKey(IntPtr hWnd,int id);

        /// <summary>
        /// Keys for Combination
        /// </summary>
        [Flags()]
        public enum KeyModifiers{
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            Windows = 8
        }

        /// <summary>
        /// Override the WndProc,When Lose focus it can also activate the registered hot keys
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312; //Press the HotKey
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    callScr();
                    break;
            }
            base.WndProc(ref m);
        }

posted on 2010-08-24 09:40  和轩僮  阅读(797)  评论(3编辑  收藏  举报

导航