線程鍵盤鉤子

public class KeyboardHook
    {
 #region ---------導入DLL--------

        //使用鉤子,須要使用WindowsAPI函數,因此要先聲明這些API函數。
        /// <summary>
        /// 安裝鍵盤鉤子
        /// </summary>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        /// <summary>
        /// 卸載鍵盤鉤子
        /// </summary>
        /// <param name="idHook"></param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);
        /// <summary>
        /// 繼續下一個鉤子
        /// </summary>
        /// <param name="idHook"></param>
        /// <param name="nCode"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <returns></returns>
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
        /// <summary>
        /// 得到得當前線程編號
        /// </summary>
        /// <returns></returns>
        [DllImport("kernel32.dll")]
        static extern int GetCurrentThreadId();
        #endregion

        #region -----聲明,定義委託-----
        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
        static int hKeyboardHook = 0;//若是hKeyboardHook不爲0則說明鉤子安裝成功
        HookProc KeyboardHookProcedure;
        #endregion

        #region ------鉤子處理程序------

        //鉤子所要處理的事情
        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr IParam)
        {
           //處理過程。。。。。。
           //
            return CallNextHookEx(hKeyboardHook, nCode, wParam, IParam);
        }
        #endregion

        #region -----啓用或卸載鉤子-----

        //鉤子安裝
        public void HookStart()
        {
            if (hKeyboardHook == 0)//若是hKeyboardHook==0,鉤子安裝失敗
            {
                //建立HookProc實例
                KeyboardHookProcedure = new HookProc(KeyboardHookProc);//若是直接用KeyboardHookProc委託會被提早釋放掉致使出錯
                //設置線程鉤子,此處參數爲2表示安裝一個掛鉤處理過程對擊鍵消息進行監視
                hKeyboardHook = SetWindowsHookEx(2, KeyboardHookProcedure, IntPtr.Zero, GetCurrentThreadId());
                if (hKeyboardHook == 0)
                {
                    throw new Exception("安裝鉤子失敗");
                }
            }
        }

        //鉤子卸載
        public void HookStop()
        {
            bool retKeyboard = true;
            if (hKeyboardHook != 0)
            {
                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);
                hKeyboardHook = 0;
            }
            if (!retKeyboard)
                throw new Exception("卸載鉤子失敗");
        }
        #endregion
    }
相關文章
相關標籤/搜索