Download SourceProgramAnd run the program
Http://file.ddvip.com/2008_11/1225788644_ddvip_7698.rar
The running interface is as follows:
NOTE 2:
It is very simple to implement this function in C ++, and there are also many classic examples to implement. Many problems may occur in C.
If you are not familiar with hooks, refer to another article I have posted.Article: Http://www.cnblogs.com/hocylan/articles/1033895.html#microsofthooktechnical topic]
Step 3
In fact, it is mainly to call Windows API
Step 1: Install the hook: setwindowshookex (wh_codes idhook, hookproc lpfn, intptr pinstance, int threadid );
Step 2: reconcile callnexthookex (intptr phookhandle, int ncode, int32 wparam, intptr lparam );
Step 3: complete common business processing and other processes
Apply the encapsulated hook to the system .......
Private void start_click (Object sender, eventargs E)
{Hook_main.installhook ("1 ");}
Private void stop_click (Object sender, eventargs E)
{This. hook_main.uninstallhook ();}
Private void stopkeyboard_click (Object sender, eventargs E)
{Hook_main.installhook ("2 ");}
Step 4: remove the hook unhookwindowshookex (intptr phookhandle );
Four importantCodeAnd explanations:
* Encapsulated hook class:
Using system;
Using system. Windows. forms;
Using system. runtime. interopservices; // must be referenced
Using system. reflection; // must be referenced
Namespace keyboardhook
{
Class hocy_hook
{
# Region private constant
/// <Summary>
/// Key status Array
/// </Summary>
Private readonly byte [] m_keystate = new byte [256];
Private string flags;
// Flag = 0 normal flag = 1 monitoring status flag = 2 shielded keyboard //
# Endregion private constant
# Region private variable
/// <Summary>
/// Mouse Hook handle
/// </Summary>
Private intptr m_pmousehook = intptr. zero;
/// <Summary>
/// Keyboard hook handle
/// </Summary>
Private intptr m_pkeyboardhook = intptr. zero;
/// <Summary>
/// Delegate an instance with a mouse hook
/// </Summary>
/// <Remarks>
/// Do not try to omit this variable, otherwise it will cause
/// Activate callbackoncollecteddelegate to host the debugging Assistant (MDA ).
/// For details, see the description of callbackoncollecteddelegate in msdn.
/// </Remarks>
Private hookproc m_mousehookprocedure;
/// <Summary>
/// Delegated instance with keyboard hook
/// </Summary>
/// <Remarks>
/// Do not try to omit this variable, otherwise it will cause
/// Activate callbackoncollecteddelegate to host the debugging Assistant (MDA ).
/// For details, see the description of callbackoncollecteddelegate in msdn.
/// </Remarks>
Private hookproc m_keyboardhookprocedure;
// Add
Public event mouseeventhandler onmouseactivity;
Private const byte vk_shift = 0x10;
Private const byte vk_capital = 0x14;
Private const byte vk_numlock = 0x90;
# Endregion private variable
# Region event Definition
/// <Summary>
/// Mouse update event
/// </Summary>
/// <Remarks> triggered when the mouse moves or the scroll wheel scrolls </remarks>
Public event mouseupdateeventhandler onmouseupdate;
/// <Summary>
/// Press the button
/// </Summary>
Public event keyeventhandler onkeydown;
/// <Summary>
/// Press and release the event
/// </Summary>
Public event keypresseventhandler onkeypress;
/// <Summary>
/// Button release event
/// </Summary>
Public event keyeventhandler onkeyup;
# Endregion event Definition
# Region private Method
/// <Summary>
/// Mouse hook processing function
/// </Summary>
/// <Param name = "ncode"> </param>
/// <Param name = "wparam"> </param>
/// <Param name = "lparam"> </param>
/// <Returns> mouse hook processing function </returns>
Private int mousehookproc (INT ncode, int32 wparam, intptr lparam)
{
If (ncode> = 0) & (onmouseactivity! = NULL ))
{
// Marshall the data from callback.
Mousehookstruct = (mousehookstruct) Marshal. ptrtostructure (lparam, typeof (mousehookstruct ));
// Detect button clicked
Mousebuttons button = mousebuttons. None;
Short mousedelta = 0;
Switch (wparam)
{
Case (INT) wm_mouse.wm_lbuttondown:
// Case wm_lbuttonup:
// Case wm_lbuttondblclk:
Button = mousebuttons. Left;
Break;
Case (INT) wm_mouse.wm_rbuttondown:
// Case wm_rbuttonup:
// Case wm_rbuttondblclk:
Button = mousebuttons. Right;
Break;
Case (INT) wm_mouse.wm_mousewheel:
// If the message is wm_mousewheel, the high-order word of mousedata member is the wheel delta.
// One wheel click is defined as wheel_delta, Which is 120.
// (Value> 16) & 0 xFFFF; retrieves the high-order word from the given 32-bit value
Mousedelta = (short) (mousehookstruct. mousedata> 16) & 0 xFFFF );
// Todo: X buttons (I havent them so was unable to test)
// If the message is wm_xbuttondown, wm_xbuttonup, wm_xbuttondblclk, wm_ncxbuttondown, wm_ncxbuttonup,
// Or wm_ncxbuttondblclk, the high-order word specifies which X button was pressed or released,
// And the low-order word is reserved. This value can be one or more of the following values.
// Otherwise, mousedata is not used.
Break;
}
// Double clicks
Int clickcount = 0;
If (button! = Mousebuttons. None)
If (wparam = (INT) wm_mouse.wm_lbuttondblclk | wparam = (INT) wm_mouse.wm_rbuttondblclk) clickcount = 2;
Else clickcount = 1;
// Generate event
Mouseeventargs E = new mouseeventargs (
Button,
Clickcount,
Mousehookstruct. Point. X,
Mousehookstruct. Point. y,
Mousedelta );
// Raise it
Onmouseactivity (this, e );
}
//*
Return WIN32API. callnexthookex (this. m_pmousehook, ncode, wparam, lparam );
}
/// <Summary>
/// Keyboard hook processing function
/// </Summary>
/// <Param name = "ncode"> </param>
/// <Param name = "wparam"> </param>
/// <Param name = "lparam"> </param>
/// <Returns> </returns>
/// <Remarks> </remarks>
Private int keyboardhookproc (INT ncode, int32 wparam, intptr lparam)
{
Switch (flags)
{
Case "2 ":
Return 1;
Break;
Case "1 ":
Break;
}
Bool handled = false;
// It was OK and someone listens to events
If (ncode> = 0) & (this. onkeydown! = NULL | this. onkeyup! = NULL | this. onkeypress! = NULL ))
{
// Read structure keyboardhookstruct at lparam
Keyboardhookstruct mykeyboardhookstruct = (keyboardhookstruct) Marshal. ptrtostructure (lparam, typeof (keyboardhookstruct ));
// Raise keydown
If (this. onkeydown! = NULL & (wparam = (INT) wm_keyboard.wm_keydown | wparam = (INT) wm_keyboard.wm_syskeydown ))
{
Keys keydata = (KEYS) mykeyboardhookstruct. vkcode;
Keyeventargs E = new keyeventargs (keydata );
This. onkeydown (this, e );
Handled = handled | E. handled;
}
// Raise keypress
If (this. onkeypress! = NULL & wparam = (INT) wm_keyboard.wm_keydown)
{
Bool isdownshift, isdowncapslock;
Try
{
Isdownshift = (WIN32API. getkeystates (vk_shift) & 0x80) = 0x80? True: false );
Isdowncapslock = (WIN32API. getkeystates (vk_capital )! = 0? True: false );
}
Catch
{
Isdowncapslock = false;
Isdownshift = false;
}
Byte [] keystate = new byte [256];
WIN32API. getkeyboardstate (keystate );
Byte [] inbuffer = new byte [2];
If (WIN32API. toascii (mykeyboardhookstruct. vkcode,
Mykeyboardhookstruct. scancode,
Keystate,
Inbuffer,
Mykeyboardhookstruct. Flags) = 1)
{
Char key = (char) inbuffer [0];
If (isdowncapslock ^ isdownshift) & char. isletter (key) Key = Char. toupper (key );
Keypresseventargs E = new keypresseventargs (key );
This. onkeypress (this, e );
Handled = handled | E. handled;
}
}
// Raise keyup
If (this. onkeyup! = NULL & (wparam = (INT) wm_keyboard.wm_keyup | wparam = (INT) wm_keyboard.wm_syskeyup ))
{
Keys keydata = (KEYS) mykeyboardhookstruct. vkcode;
Keyeventargs E = new keyeventargs (keydata );
This. onkeyup (this, e );
Handled = handled | E. handled;
}
}
// If event handled in application do not handoff to other listeners
If (handled)
Return 1;
Else
Return WIN32API. callnexthookex (this. m_pkeyboardhook, ncode, wparam, lparam );
}
# Endregion private Method
# Region Public Method
/// <Summary>
/// Install the hook
/// </Summary>
/// <Returns> </returns>
Public bool installhook (string flagsinfo)
{
This. Flags = flagsinfo;
Intptr pinstance = marshal. gethinstance (assembly. getexecutingassembly (). manifestmodule );
// Pinstance = (intptr) 4194304;
// Note: In most cases, pinstanc cannot install the hook. Check whether the value is 4194304. You can directly obtain
// Intptr pinstanc2 = marshal. gethinstance (assembly. getexecutingassembly ());
// Assembly. getexecutingassembly (). getmodules () [0]
// Install the mouse hook
If (this. m_pmousehook = intptr. Zero)
{
This. m_mousehookprocedure = new hookproc (this. mousehookproc );
This. m_pmousehook = WIN32API. setwindowshookex (wh_codes.wh_mouse_ll, this. m_mousehookprocedure, pinstance, 0 );
// Wh_codes.wh_mouse_ll indicates a global hook, that is, a system hook. Otherwise, it should be wh_codes.wh_keyboard, that is, a common hook.
If (this. m_pmousehook = intptr. Zero)
{
This. uninstallhook ();
Return false;
}
}
If (this. m_pkeyboardhook = intptr. Zero) // install the keyboard hook
{
This. m_keyboardhookprocedure = new hookproc (this. keyboardhookproc );
// Wh_codes.wh_keyboard_ll indicates a global hook, that is, a system hook. Otherwise, it should be wh_codes.wh_keyboard, that is, a common hook.
This. m_pkeyboardhook = WIN32API. setwindowshookex (wh_codes.wh_keyboard_ll, this. m_keyboardhookprocedure, pinstance, 0 );
If (this. m_pkeyboardhook = intptr. Zero)
{
This. uninstallhook ();
Return false;
}
}
Return true;
}
/// <Summary>
/// Uninstall the hook
/// </Summary>
/// <Returns> </returns>
Public bool uninstallhook ()
{
Bool result = true;
If (this. m_pmousehook! = Intptr. Zero)
{
Result = (WIN32API. unhookwindowshookex (this. m_pmousehook) & result );
This. m_pmousehook = intptr. zero;
}
If (this. m_pkeyboardhook! = Intptr. Zero)
{
Result = (WIN32API. unhookwindowshookex (this. m_pkeyboardhook) & result );
This. m_pkeyboardhook = intptr. zero;
}
Return result;
}
# Endregion public Method
# Region Constructor
/// <Summary>
/// Hook
/// </Summary>
/// <Remarks> This class simply implements wh_keyboard_ll and wh_mouse_ll </remarks>
Public hocy_hook ()
{
WIN32API. getkeyboardstate (this. m_keystate );
}
# Endregion Constructor
}
}