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

      
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);
        }

原文地址:https://www.cnblogs.com/vic_lu/p/1806986.html