A class for global acquisition of the mouse and keyboard

Source: Internet
Author: User

With the start method of this class, you can start to capture global events and corresponding parameter information of the keyboard and mouse, which is also called the hook program:
I used to see a program written by a senior developer. I started to understand it. After my "anti-translation", I understood it better and shared it with you:

Class for getting the mouse message:

Using system;
Using system. runtime. interopservices;
Using system. reflection;
Using system. Threading;
Using system. Windows. forms;

Namespace hookglobal
{
 
/// <Summary>
/// This class allows you to get all mouse events of a running program.
/// And trigger a. Net mouse event with the mouseeventargs parameter so that you can easily use this information
/// </Summary>
/// <Remarks>
/// </Remarks>
Public class mousehook
{
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;

// Global events
Public event mouseeventhandler onmouseactivity;

Static int hmousehook = 0; // mouse hook handle

// Mouse constant
Public const int wh_mouse_ll = 14; // mouse hook constant

Hookproc mousehookprocedure; // declare the type of the mouse hook event.

// Declare the mail type of a point
[Structlayout (layoutkind. Sequential)]
Public Class Point
{
Public int X;
Public int y;
}

// Declare the delivery structure type of the mouse hook
[Structlayout (layoutkind. Sequential)]
Public class mousehookstruct
{
Public point pt;
Public int hwnd;
Public int whittestcode;
Public int dwextrainfo;
}

// Device Hook Function
[Dllimport ("user32.dll", charset = charset. Auto, callingconvention = callingconvention. stdcall)]
Public static extern int setwindowshookex (INT idhook, hookproc lpfn, intptr hinstance, int threadid );

// Remove the hook function
[Dllimport ("user32.dll", charset = charset. Auto, callingconvention = callingconvention. stdcall)]
Public static extern bool unhookwindowshookex (INT idhook );

// The next hook function
[Dllimport ("user32.dll", charset = charset. Auto, callingconvention = callingconvention. stdcall)]
Public static extern int callnexthookex (INT idhook, int ncode, int32 wparam, intptr lparam );

Public Delegate int hookproc (INT ncode, int32 wparam, intptr lparam );

/// <Summary>
/// The constructor of Moxi constructs the instance of the current class.
/// </Summary>
Public mousehook ()
{
// Start ();
}

// Destructor.
~ Mousehook ()
{
Stop ();
}

Public void start ()
{
// Install the mouse hook
If (hmousehook = 0)
{
// Generate a hookproc instance.
Mousehookprocedure = new hookproc (mousehookproc );

Hmousehook = setwindowshookex (wh_mouse_ll, mousehookprocedure, Marshal. gethinstance (assembly. getexecutingassembly (). getmodules () [0]), 0 );

// If the device fails to stop the hook
If (hmousehook = 0)
{
Stop ();
Throw new exception ("setwindowshookex failed .");
}
}
}

Public void stop ()
{
Bool retmouse = true;
If (hmousehook! = 0)
{
Retmouse = unhookwindowshookex (hmousehook );
Hmousehook = 0;
}

// If the hook fails to be removed
If (! (Retmouse) throw new exception ("unhookwindowshookex failed .");
}

Private int mousehookproc (INT ncode, int32 wparam, intptr lparam)
{
// If the message is normal and the user wants to listen to the mouse
If (ncode> = 0) & (onmouseactivity! = NULL ))
{
Mousebuttons button = mousebuttons. None;
Int clickcount = 0;

Switch (wparam)
{
Case wm_lbuttondown:
Button = mousebuttons. Left;
Clickcount = 1;
Break;
Case wm_lbuttonup:
Button = mousebuttons. Left;
Clickcount = 1;
Break;
Case wm_lbuttondblclk:
Button = mousebuttons. Left;
Clickcount = 2;
Break;
Case wm_rbuttondown:
Button = mousebuttons. Right;
Clickcount = 1;
Break;
Case wm_rbuttonup:
Button = mousebuttons. Right;
Clickcount = 1;
Break;
Case wm_rbuttondblclk:
Button = mousebuttons. Right;
Clickcount = 2;
Break;
}

// Obtain the mouse information from the callback function
Mousehookstruct mymousehookstruct = (mousehookstruct) Marshal. ptrtostructure (lparam, typeof (mousehookstruct ));
Mouseeventargs E = new mouseeventargs (button, clickcount, mymousehookstruct.pt. X, mymousehookstruct.pt. Y, 0 );
Onmouseactivity (this, e );
}
Return callnexthookex (hmousehook, ncode, wparam, lparam );
}
}
}

Class for obtaining keyboard messages:

Using system;
Using system. runtime. interopservices;
Using system. reflection;
Using system. Threading;
Using system. Windows. forms;

Namespace hookglobal
{
 
/// <Summary>
/// This class allows you to get all keyboard or mouse events of a running program.
/// And trigger a. Net event with keyeventargs and mouseeventargs parameters so that you can easily use this information
/// </Summary>
/// <Remarks>
/// Modify: lihx
/// Modification time: 04.11.8
/// </Remarks>
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;

// Global events
Public event keyeventhandler onkeydownevent;
Public event keyeventhandler onkeyupevent;
Public event keypresseventhandler onkeypressevent;

Static int hkeyboardhook = 0; // keyboard hook handle

// Mouse constant
Public const int wh_keyboard_ll = 13; // keyboard hook constant

Hookproc keyboardhookprocedure; // declare the type of the keyboard hook event.

// Declare the mail structure type of the keyboard hook
[Structlayout (layoutkind. Sequential)]
Public class keyboardhookstruct
{
Public int vkcode; // a virtual keyboard code between 1 and 254
Public int scancode; // indicates the hardware scan code.
Public int flags;
Public int time;
Public int dwextrainfo;
}
// Device Hook Function
[Dllimport ("user32.dll", charset = charset. Auto, callingconvention = callingconvention. stdcall)]
Public static extern int setwindowshookex (INT idhook, hookproc lpfn, intptr hinstance, int threadid );

// Remove the hook function
[Dllimport ("user32.dll", charset = charset. Auto, callingconvention = callingconvention. stdcall)]
Public static extern bool unhookwindowshookex (INT idhook );

// The next hook function
[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>
/// The constructor of ink recognition constructs the instance of the current class and runs it automatically.
/// </Summary>
Public keybordhook ()
{
Start ();
}

// Destructor.
~ Keybordhook ()
{
Stop ();
}

Public void start ()
{
// Install the keyboard hook
If (hkeyboardhook = 0)
{
Keyboardhookprocedure = new hookproc (keyboardhookproc );
Hkeyboardhook = setwindowshookex (wh_keyboard_ll, keyboardhookprocedure, Marshal. gethinstance (assembly. getexecutingassembly (). getmodules () [0]), 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 the hook fails to be removed
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 ));
// Trigger onkeydownevent
If (onkeydownevent! = NULL & (wparam = wm_keydown | wparam = wm_syskeydown ))
{
Keys keydata = (KEYS) mykeyboardhookstruct. vkcode;
Keyeventargs E = new keyeventargs (keydata );
Onkeydownevent (this, e );
}

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

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

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.