C # example code that uses hooks to monitor mouse keyboard events

Source: Internet
Author: User
Tags windows hosting

If this program in 10几 years ago, QQ has just arisen, with this code, you can realize the theft number.

Of course the use of hooks we are more to achieve the "global shortcut key" requirements.

such as the program to minimize the hidden after the "some shortcut key" to start it.

Hook (Hook), in layman's words, she can capture your keyboard and mouse related action messages.

About hook related code on the net a search a basket, this is tidy up more perfect and use most convenient.

    Declare Wrapper managed Point class.        [StructLayout (LayoutKind.Sequential)] public class Point {public int x;    public int y;    }//declare Wrapper managed MouseHookStruct class.        [StructLayout (LayoutKind.Sequential)] public class MouseHookStruct {public Point pt;        public int hwnd;        public int whittestcode;    public int dwextrainfo;    }//declare Wrapper managed Keyboardhookstruct class. [StructLayout (LayoutKind.Sequential)] public class Keyboardhookstruct {public int vkcode;//specifies a virt Ual-key code.         The code must is a value in the range 1 to 254. public int scancode;         Specifies a hardware scan code for the key. public int flags;        Specifies the EXTENDED-KEY flag, event-injected flag, context code, and Transition-state flag. public int time;        Specifies the time stamp for this message. public int dwextrainfo; Specifies extra information associated with the MeSsage.        } public class Globalhook {public delegate int HookProc (int nCode, Int32 wParam, IntPtr lParam);        public delegate int Globalhookproc (int nCode, Int32 wParam, IntPtr lParam);        Public Globalhook () {//start ();        } ~globalhook () {Stop ();        } public event MouseEventHandler onmouseactivity;        public event Keyeventhandler KeyDown;        public event Keypresseventhandler KeyPress;        public event Keyeventhandler KeyUp;        <summary>//Define the handle of the mouse hook.        </summary> static int _hmousehook = 0;        <summary>///define keyboard hook handle///</summary> static int _hkeyboardhook = 0;        public int Hmousehook {get {return _hmousehook;}        } public int Hkeyboardhook {get {return _hkeyboardhook;} }///<summary>//mouse hook constants (from MicroSoft SDK Winuser.h)///</summary> Public const int WH_MOUSE_LL = 14; <summary>///keyboard hook constants (from Microsoft SDK Winuser.h)///</summary> Public const INT        Wh_keyboard_ll = 13;        <summary>///define a delegate object for the mouse process///</summary> Globalhookproc mousehookprocedure;        <summary>///delegate object for keyboard processing///</summary> Globalhookproc keyboardhookprocedure; Import window Hook extension method Import///<summary>///install hook method///</summary> [DllImport ("User32. DLL ", CharSet = CharSet.Auto, callingconvention = callingconvention.stdcall)] public static extern int Setwindowsho                        Okex (int idhook, Globalhookproc lpfn,intptr hinstance, int threadId); <summary>///Uninstall Hook method///</summary> [DllImport ("user32.dll", CharSet = CharSet.Auto,  CallingConvention = Callingconvention.stdcall)]      public static extern bool UnhookWindowsHookEx (int idhook);        Import for CallNextHookEx.        <summary>/////Use this function to hook information to the next hook procedure in the chain. </summary> [DllImport ("user32.dll", CharSet = CharSet.Auto, callingconvention = Callingconvention.stdcall        )] public static extern int CallNextHookEx (int idhook, int nCode, Int32 wParam, IntPtr lParam);                public bool Start () {//install Mouse hook if (_hmousehook = = 0) {                Create an instance of HookProc.                Mousehookprocedure = new Globalhookproc (MOUSEHOOKPROC); try {_hmousehook = SetWindowsHookEx (Wh_mouse_ll, mousehookproced Ure, Marshal.gethinstance (assembly.getexecutingassembly ().                GetModules () [0]), 0);         } catch (Exception err) {}       If installing the mouse hook fails if (_hmousehook = = 0) {Stop ();                    return false;                throw new Exception ("SetWindowsHookEx failed.");  }}//Install the keyboard hook if (_hkeyboardhook = = 0) {keyboardhookprocedure =                New Globalhookproc (KEYBOARDHOOKPROC); try {_hkeyboardhook = SetWindowsHookEx (Wh_keyboard_ll, Keyboardh Ookprocedure, Marshal.gethinstance (assembly.getexecutingassembly ().                GetModules () [0]), 0); } catch (Exception err2) {}//If the install keyboard hook fails if (_hkeyboardhook =                    = 0) {Stop ();                    return false;            throw new Exception ("SetWindowsHookEx ist failed.");    }} return true;            } public void Stop () {bool Retmouse = true;            bool Retkeyboard = true;                if (_hmousehook! = 0) {retmouse = UnhookWindowsHookEx (_hmousehook);            _hmousehook = 0;                } if (_hkeyboardhook! = 0) {Retkeyboard = UnhookWindowsHookEx (_hkeyboardhook);            _hkeyboardhook = 0;            }//if UnhookWindowsHookEx fails. if (! (            Retmouse && retkeyboard) {//throw new Exception ("UnhookWindowsHookEx ist failed."); }}///<summary>//uninstall hook, if the process is forced to end, record the last hook ID and unload it according to the hook ID//            /</summary> public void Stop (int hmousehook, int hkeyboardhook) {if (Hmousehook! = 0)            {UnhookWindowsHookEx (Hmousehook); } if (Hkeyboardhook! = 0)            {UnhookWindowsHookEx (Hkeyboardhook);        }} Private Const int wm_mousemove = 0x200;        Private Const int WM_LBUTTONDOWN = 0x201;        Private Const int wm_rbuttondown = 0x204;        Private Const int wm_mbuttondown = 0x207;        Private Const int wm_lbuttonup = 0x202;        Private Const int wm_rbuttonup = 0x205;        Private Const int wm_mbuttonup = 0x208;        Private Const int WM_LBUTTONDBLCLK = 0x203;        Private Const int WM_RBUTTONDBLCLK = 0x206;        Private Const int WM_MBUTTONDBLCLK = 0x209; private int MouseHookProc (int nCode, Int32 wParam, IntPtr lParam) {if (nCode >= 0) && (onmo                useactivity = null)) {MouseButtons button = Mousebuttons.none; Switch (wParam) {case WM_LBUTTONDOWN://Left button pressed//case Wm_lbutto NUP://Right-click//case wm_lbuttondblclk://SamePress button = MouseButtons.Left;                    Break                         Case Wm_rbuttondown://case wm_rbuttonup://case wm_rbuttondblclk:                        button = Mousebuttons.right;                Break                } int clickcount = 0;                        if (Button! = Mousebuttons.none) if (WParam = = WM_LBUTTONDBLCLK | | wParam = = WM_RBUTTONDBLCLK)                    Clickcount = 2;                else Clickcount = 1;                Marshall the data from callback. MouseHookStruct mymousehookstruct = (mousehookstruct) marshal.ptrtostructure (LParam, typeof (Mousehookstr                UCT)); MouseEventArgs e = new MouseEventArgs (button, Clickcount, mymous                Ehookstruct.pt.x, Mymousehookstruct.pt.y, 0); OnmouseacTivity (this, e);        } return CallNextHookEx (_hmousehook, NCode, WParam, LParam); }//the toascii function translates the specified Virtual-key code and keyboard state to the corresponding CHARACTE R or characters. The function translates the code using the input language and physical keyboard layout identified by the keyboard layout h        Andle. [DllImport ("user32")] public static extern int Toascii (int. Uvirtkey,//[in] Specifies the Virtual-key code to be TR             Anslated. int Uscancode,//[in] Specifies the hardware scan code of the key to be translated.             The High-order bit of this value is set if the key was up (not pressed). Byte[] lpbkeystate,//[in] Pointer to a 256-byte array that contains the current keyboard state. Each element (byte) in the array contains the state of one key. If the High-order bit of a byte is set, the key was down (pressed). The low bit, if set, indicates the key is toggled on. In the This function, Only the toggle bit of the CAPS LOCK key is relevant.            The toggle state of the NUM lock and SCROLL lock keys are ignored.             Byte[] Lpwtranskey,//[out] Pointer to the buffer that receives the translated character or characters. int fustate); Specifies whether a menu is active.         This parameter must are 1 if a menu is active, or 0 otherwise.         The Getkeyboardstate function copies the status of the specified buffer.        [DllImport ("user32")] public static extern int getkeyboardstate (byte[] pbkeystate);        Private Const int WM_KEYDOWN = 0x100;        Private Const int WM_KEYUP = 0X101;        Private Const int wm_syskeydown = 0x104;        Private Const int wm_syskeyup = 0x105; private int Keyboardhookproc (int nCode, Int32 wParam, IntPtr lParam) {//It was OK and someone listens To Events if ((NCode >= 0) && (KeyDown! = NULL | | KeyUp! = NULL | |       KeyPress = null))     {Keyboardhookstruct mykeyboardhookstruct = (keyboardhookstruct) marshal.ptrtostruct                Ure (LParam, typeof (Keyboardhookstruct));                Raise KeyDown if (KeyDown! = null && (WParam = = Wm_keydown | | wParam = wm_syskeydown))                    {Keys keyData = (keys) Mykeyboardhookstruct.vkcode;                    KeyEventArgs e = new KeyEventArgs (keyData);                KeyDown (this, e);                    }//Raise KeyPress if (KeyPress! = null && WParam = = wm_keydown) {                    byte[] keyState = new byte[256];                    Getkeyboardstate (keyState);                    byte[] Inbuffer = new byte[2]; if (Toascii (Mykeyboardhookstruct.vkcode, Mykeyboardhookstruct.scancode, KeyS Tate, Inbuffer, Mykeyboardhookstruct.flags) = = 1) {KeyPressEventArgs e = new KeyPressEventArgs ((char) inbuffer[                        0]);                    KeyPress (this, e);  }}//Raise KeyUp if (KeyUp! = null && (WParam = = Wm_keyup | | wParam                    = = Wm_syskeyup)) {Keys keyData = (keys) Mykeyboardhookstruct.vkcode;                    KeyEventArgs e = new KeyEventArgs (keyData);                KeyUp (this, e);        }} return CallNextHookEx (_hkeyboardhook, NCode, WParam, LParam); }    }

  


Attention:
If the return value of SetWindowsHookEx appears to be 0 in the run, this is because of the. NET debug mode issue, which is done by disabling the host process and opening the project in Visual Studio.
On the Project menu, click Properties.
Click the Debug tab.
Clear the Enable Visual Studio host process (enable Windows hosting process) check box or tick enable unmanaged code debugging

Examples of Use:

<summary>///declaration of a Hook object///</summary> globalhook hook;            private void Form1_Load (object sender, EventArgs e) {btninstallhook.enabled = true;            btnuninstall.enabled = false;                Initialize the Hook object if (hook = = null) {hook = new Globalhook (); Hook.                KeyDown + = new Keyeventhandler (Hook_keydown); Hook.                KeyPress + = new Keypresseventhandler (hook_keypress); Hook.                KeyUp + = new Keyeventhandler (hook_keyup); Hook.            Onmouseactivity + = new MouseEventHandler (hook_onmouseactivity); }} private void Form1_formclosing (object sender, FormClosingEventArgs e) {if (Btnuninsta ll. Enabled = = True) {hook.            Stop (); }} private void Btninstallhook_click (object sender, EventArgs e) {if (Btninstallhook.ena              bled = = True) {  BOOL R = Hook.                Start ();                    if (r) {btninstallhook.enabled = false;                    Btnuninstall.enabled = true;                MessageBox.Show ("Installation hook succeeded!");                } else {MessageBox.Show ("Installation hook failed!"); }}} private void Btnuninstall_click (object sender, EventArgs e) {if (btnunin Stall. Enabled = = True) {hook.                Stop ();                btnuninstall.enabled = false;                Btninstallhook.enabled = true;            MessageBox.Show ("Uninstall Hook succeeded!"); }}///<summary>//Mouse Move Event///</summary> void Hook_onmouseactivity (objec        T sender, MouseEventArgs e) {lbmousestate.text = "X:" + e.x + "Y:" + e.y; }///<summary>//keyboard lifted///</summary> void Hook_keyup (object sender, KeyeventaRGS e) {lbkeystate.text = "keyboard lifted," + e.keydata.tostring () + "Key code:" + E.keyvalue; }///<summary>//keyboard input///</summary> void Hook_keypress (object sender, KeyPress EventArgs e) {}//<summary>//keyboard pressed///</summary> void Hook_keydown (ob        Ject sender, KeyEventArgs e) {lbkeystate.text = "keyboard pressed," + e.keydata.tostring () + "Key code:" + E.keyvalue; }

If you want to capture the mouse down raised event, you can modify the MouseHookProc method related code for the Globalhook class

Sample code Download

C # example code that uses hooks to monitor mouse keyboard events

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.