C#滑鼠鍵盤鉤子

來源:互聯網
上載者:User

標籤:style   blog   color   使用   os   art   

using System;using System.Collections.Generic;using System.Reflection;using System.Runtime.InteropServices;using System.Text;using System.Windows.Forms;namespace ICS.Common{    ///   <summary>     ///   這個類可以讓你得到一個在運行中程式的所有鍵盤或滑鼠事件     ///   並且引發一個帶KeyEventArgs參數的.NET事件以便你很容易使用這些資訊     ///   </summary>    public class KeyBordHook    {        private const int WM_KEYDOWN = 0x100;        private const int WM_KEYUP = 0x101;        private const int WM_SYSKEYDOWN = 0x104;        private const int WM_SYSKEYUP = 0x105;        //全域的事件         public event KeyEventHandler OnKeyDownEvent;        public event KeyEventHandler OnKeyUpEvent;        public event KeyPressEventHandler OnKeyPressEvent;        static int hKeyboardHook = 0;   //鍵盤鉤子控制代碼         //滑鼠常量         public const int WH_KEYBOARD_LL = 13;   //keyboard   hook   constant           HookProc KeyboardHookProcedure;   //聲明鍵盤鉤子事件類型.         //聲明鍵盤鉤子的封送結構類型         [StructLayout(LayoutKind.Sequential)]        public class KeyboardHookStruct        {            public int vkCode;   //表示一個在1到254間的虛似鍵盤碼             public int scanCode;   //表示硬體掃描碼             public int flags;            public int time;            public int dwExtraInfo;        }        //裝置鉤子的函數         [DllImport("user32.dll ", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);        //卸下鉤子的函數         [DllImport("user32.dll ", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]        public static extern bool UnhookWindowsHookEx(int idHook);        //下一個鉤掛的函數         [DllImport("user32.dll ", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);        [DllImport("user32 ")]        public static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);        [DllImport("user32 ")]        public static extern int GetKeyboardState(byte[] pbKeyState);        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);        ///   <summary>         ///   墨認的建構函式構造當前類的執行個體並自動的運行起來.         ///   </summary>         public KeyBordHook()        {            Start();        }        //解構函式.         ~KeyBordHook()        {            Stop();        }        public void Start()        {            //安裝鍵盤鉤子               if (hKeyboardHook == 0)            {                KeyboardHookProcedure = new HookProc(KeyboardHookProc);                hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardHookProcedure, Marshal.GetHINSTANCE(Assembly.GetExecutingAssembly().ManifestModule), 0);                if (hKeyboardHook == 0)                {                    Stop();                    throw new Exception("SetWindowsHookEx   ist   failed. ");                }            }        }        public void Stop()        {            bool retKeyboard = true;            if (hKeyboardHook != 0)            {                retKeyboard = UnhookWindowsHookEx(hKeyboardHook);                hKeyboardHook = 0;            }            //如果卸下鉤子失敗             if (!(retKeyboard)) throw new Exception("UnhookWindowsHookEx   failed. ");        }        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)        {            if ((nCode >= 0) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null))            {                KeyboardHookStruct MyKeyboardHookStruct = (KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(KeyboardHookStruct));                //引發OnKeyDownEvent                 if (OnKeyDownEvent != null && (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN))                {                    Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;                    KeyEventArgs e = new KeyEventArgs(keyData);                    OnKeyDownEvent(this, e);                }                //引發OnKeyPressEvent                 if (OnKeyPressEvent != null && wParam == WM_KEYDOWN)                {                    byte[] keyState = new byte[256];                    GetKeyboardState(keyState);                    byte[] inBuffer = new byte[2];                    if (ToAscii(MyKeyboardHookStruct.vkCode,                      MyKeyboardHookStruct.scanCode,                      keyState,                      inBuffer,                      MyKeyboardHookStruct.flags) == 1)                    {                        KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);                        OnKeyPressEvent(this, e);                    }                }                //引發OnKeyUpEvent                 if (OnKeyUpEvent != null && (wParam == WM_KEYUP || wParam == WM_SYSKEYUP))                {                    Keys keyData = (Keys)MyKeyboardHookStruct.vkCode;                    KeyEventArgs e = new KeyEventArgs(keyData);                    OnKeyUpEvent(this, e);                }            }            return CallNextHookEx(hKeyboardHook, nCode, wParam, lParam);        }    }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.