"Turn" hook Hooks C # instance

Source: Internet
Author: User

"Turn" hook Hooks C # instance

Turn over the article, the source has not known, but this step is relatively clear, it was posted.

One. Written in the first

The contents of this article only want to explain the use of hooks in the most popular language, specific to the hook detailed introduction can refer to the following URL:

Http://www.microsoft.com/china/community/program/originalarticles/techdoc/hook.mspx

Two. Check out the hooks.

Literally, hooks are meant to hook up something, and in a program you can use hooks to process some Windows messages ahead of time.

Example: There is a form,form in a textbox, we want to let the user in the TextBox input, regardless of which key to the keyboard, the textbox is always displayed as "A", then we can use the hook to monitor the keyboard message, First to the Windows Hook list to add a self-written hook to listen to the keyboard message, as long as a press the keyboard will produce a keyboard message, our hook before the message to the TextBox intercept it, let the textbox display a "a", and then end the message, So the textbox always gets the "A".

message interception Order: Since the interception of messages, always have to have first, the hooks are added to the list of hooks in order to determine the order of message interception. That is, the last hook to join the list is the first to get the message.

Intercept range: hooks are divided into thread hooks and global hooks, thread hooks can intercept only messages from this thread, and global hooks intercept entire system messages. I think we should try to use thread hooks, global hooks can affect other programs if used improperly.

Three. Start popular

Here is a thread hook with the simple example mentioned above.

First step: declaring API functions

Using hooks, you need to use the WINDOWSAPI function, so declare these API functions first.

//Mounting hooks[DllImport ("user32.dll", CharSet=CharSet.Auto, Callingconvention=callingconvention.stdcall)] Public Static extern intSetWindowsHookEx (intIdhook, HookProc lpfn, IntPtr hinstance,intTHREADID);//Unload hooks[DllImport ("user32.dll", CharSet=CharSet.Auto, Callingconvention=callingconvention.stdcall)] Public Static extern BOOLUnhookWindowsHookEx (intIdhook);//Continue to the next hook[DllImport ("user32.dll", CharSet=CharSet.Auto, Callingconvention=callingconvention.stdcall)] Public Static extern intCallNextHookEx (intIdhook,intNCode, Int32 WParam, IntPtr lParam);//Get current thread number[DllImport ("Kernel32.dll")]Static extern intGetCurrentThreadID ();

Declare the API function, and you can call it directly later.

The second step: declaration, definition.

 Public Delegate int HookProc (int nCode, Int32 WParam, IntPtr lParam); Static int hkeyboardhook = 0; HookProc keyboardhookprocedure;

To explain the delegate first, the hook must use a standard hook, the hook is a way, is to deal with the above example mentioned in the TextBox to show "a" operation.

The hook must follow the structure definition of hookproc (int nCode, Int32 wParam, IntPtr LParam), and three parameters will get the data about the message.

When the SetWindowsHookEx function is used to install the hook, the handle of the hook is returned, and the Hkeyboardhook variable records the returned handle, if Hkeyboardhook is not 0, the hook installation succeeds.

Step Three: write the hook thread

The hook is what the hook is going to do.

Private int Keyboardhookproc (int nCode, Int32 WParam, IntPtr lParam) {if (nCode >= 0)    {        textbox1. Text = "A";        return 1;    } return CallNextHookEx (Hkeyboardhook, NCode, WParam, LParam); }

We write a method that returns an int value, including three parameters. As shown above, the code conforms to the standard of the hook thread.

The ncode parameter is the hook code, which uses this parameter to determine the task, and the value of the parameter depends on the hook type.

The wparam and lparam parameters contain the message information from which we can extract the required information.

The content of the method can be written as needed, we need a TextBox to display "A", then we will write here. When the hook intercepts the message, it calls the hook, and the program ends before it goes down. Intercept the message what to do is to see the return value of the child, if return 1, the end of the message, this message ends, no longer pass. If 0 is returned or the CallNextHookEx function is called, the message is sent out of the hook, which is passed to the true recipient of the message.

Fourth Step: install hooks, uninstall hooks

The preparations are complete, and the rest is to put the hooks into the chain list.

We can write two ways to invoke the appropriate location in the program. The code is as follows:

//Mounting hooks Public voidHookstart () {if(Hmousehook = = 0) {//Create HookProc instancesMousehookprocedure =NewHookProc (MouseHookProc);//Set Thread hooksHmousehook = SetWindowsHookEx (2, Keyboardhookprocedure, IntPtr.Zero, Getcurrentthrea Did ());//If the set hook failsif(Hmousehook = = 0) {hookstop ();Throw NewException ("SetWindowsHookEx failed."); }    }}//Unload hooks Public voidHookstop () {BOOLRetkeyboard =true;if(Hkeyboardhook! = 0)        {Retkeyboard = UnhookWindowsHookEx (Hkeyboardhook);    Hkeyboardhook = 0; }if(! (Retmouse && Retkeyboard))Throw NewException ("UnhookWindowsHookExFailed. ");}

The key to installing hooks and unloading hooks is the SetWindowsHookEx and UnhookWindowsHookEx methods.

SetWindowsHookEx (int idhook, HookProc lpfn, IntPtr hinstance, int threadId) functions add hooks to the list of hooks to illustrate four parameters:

idhook Hook type, that is, determine the hook to listen to what message, the above code is set to 2, that is, listening to keyboard messages and thread hooks, if the global Hook listening keyboard message should be set to 13, Thread hook monitoring mouse message set to 7, Global Hook monitoring Mouse message set to 14.

LPFN The address pointer of the hook path. If the dwThreadID parameter is 0 or an identity of a thread created by another process, LPFN must point to the hook in the DLL. In addition, LPFN can point to a section of the current process's hook code. The entry address of the hook function, which is called when the hook is hooked to any message.

A handle to the hinstance application instance. Identifies the DLL that contains the Cheng referred to by LPFN. If ThreadID identifies a thread created by the current process, and the subroutine code is in the current process, hinstance must be null. It is easy to set an instance handle for this application.

threaded The identifier of the thread associated with the installed hook child threads. If 0, the hook thread is associated with all threads, which is the global hook.

The SetWindowsHookEx method in the above code installs a thread hook, using the GetCurrentThreadID () function to get the current thread ID, and the hook listens only to the current thread's keyboard message.

The UnhookWindowsHookEx (int idhook) function is used to unload hooks, and unloading hooks is independent of the order in which the hooks are added, not LIFO.

Four. Complications

Install global Hooks

The above is a thread hook, if you want to use a global hook on the hook installation slightly different. As follows:

SetWindowsHookEx (13,keyboardhookprocedure,           marshal.gethinstance (assembly.getexecutingassembly (). GetModules () [0]), 0)

This statement defines the global hooks.

Child process Message Processing

The hook can get two parameters Wprama and lParam about message information. How do you turn these two parameters into a message that we're more likely to understand?

For mouse messages, we can define the following structure:

 Public struct  Public  Public IntPtr HWnd;  Public UINT Whittestcode;  Public int dwExtraInfo;}

For keyboard messages, we can define the following structure:

 Public struct keymsg{publicintpublicint Scancode;  publicintpublicintpublicint dwExtraInfo; }

Then we can convert the LPARAM data into MSG or KEYMSG structure data in the sub-thread with the following statement

typeof typeof (keymsg));

This can be more convenient to get mouse messages or keyboard messages related information, such as p is the mouse coordinates, HWND is the mouse click on the handle of the control, Vkcode is the key code.

NOTE: This statement can be used for thread hooks and global hooks that listen for mouse messages, but there is an error in using thread hooks to listen for keyboard messages and is currently looking for the cause.

If it is the thread hook that listens to the keyboard message, we can determine whether the key is pressed or lifted according to the positive or negative of the lparam value, and determines which key is pressed according to the wparam value.

Press the key

Keys keyData = (keys) WParam;

if (Lparam.toint32 () > 0)

{

The keyboard presses

}

if (Lparam.toint32 () < 0)

{

Keyboard Lift up

}

If it is a global hook that listens for keyboard messages, the keys are pressed or lifted to determine according to the wparam value.

WParam = = 0x100//keyboard pressed

WParam = = 0x101//keyboard lifted

"Turn" hook Hooks C # instance

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.