Hook C # instance

Source: Internet
Author: User

I. Preface

The content of this article only describes how to use hooks in the most popular language. For details about hooks, refer to the following URL:

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

II. Hook

Literally, hooks are intended to hook up something. In a program, hooks can be used to process Windows messages in advance.

Example:There is A Form, and Form has A TextBox. When we want users to input it in the TextBox, no matter which key on the keyboard, "A" is always displayed in the TextBox ", in this case, you can use a hook to listen to keyboard messages. First, add a hook to the hook linked list of Windows to listen to keyboard messages. If you press the keyboard, a keyboard message is generated, our Hook intercepts the message before it passes to the TextBox, so that the TextBox displays A "A" and ends the message. In this way, the TextBox always gets "".

Message interception sequence:Since a message is intercepted, there must always be a few first, and then the hook is added to the hook linked list to determine the order of message interception. That is to say, the hook added to the linked list first obtains the message.

Interception range:Hooks are divided into thread hooks and global hooks. Thread hooks can only intercept messages of the current thread, and global hooks can intercept messages of the entire system. I think thread hooks should be used whenever possible. Improper use of global hooks may affect other programs.

3. Getting started

Here is a simple example of a thread hook.

Step 1:Declare API functions

To use hooks, you must use WindowsAPI functions. Therefore, you must declare these API functions first.

// Install the hook [DllImport ("user32.dll", CharSet = CharSet. auto, CallingConvention = CallingConvention. stdCall)] public static extern int SetWindowsHookEx (int idHook, HookProc lpfn, IntPtr hInstance, int threadId); // uninstall hook [DllImport ("user32.dll", CharSet = CharSet. auto, CallingConvention = CallingConvention. stdCall)] public static extern bool UnhookWindowsHookEx (int idHook); // continue to the next hook [DllImport ("user32.dll", CharSet = CharSet. auto, CallingConvention = CallingConvention. stdCall)] public static extern int CallNextHookEx (int idHook, int nCode, Int32 wParam, IntPtr lParam); // obtain the current thread number [DllImport ("kernel32.dll")] static extern int GetCurrentThreadId ();

Declare the API function and then call it directly.

Step 2:Declaration and definition.

public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);static int hKeyboardHook = 0; HookProc KeyboardHookProcedure;

First, explain the delegate. The hook must use A standard hook sub-process. The hook sub-process is A method that handles the operations mentioned in the preceding example to display "A" on the TextBox.

The hooks must be defined according to the HookProc (int nCode, Int32 wParam, IntPtr lParam) structure. The three parameters will get the data about the message.

After the hook is successfully installed using the SetWindowsHookEx function, the handle of the hook sub-process is returned. The hKeyboardHook variable records the returned handle. If the hKeyboardHook is not 0, the hook is successfully installed.

Step 3:Write hook Program

The hook process 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); }

Let's write a method and return an int value, which includes three parameters. As shown in the code above, it complies with the hook program standard.

The nCode parameter is the Hook code. The Hook program uses this parameter to determine the task. The value of this parameter depends on the Hook type.

The wParam and lParam parameters contain message information, from which we can extract the required information.

The content of the method can be compiled as needed. We need TextBox to display "A", so we will write it here. After the Hook intercepts the message, it will call the hook sub-program. After the program ends, it will proceed. How to process the intercepted message depends on the return value of the Child Program. If 1 is returned, the message ends. This message is no longer transmitted until now. If the return value is 0 or the CallNextHookEx function is called, the message returns this hook and continues to be transmitted, that is, to the real receiver of the message.

Step 4:Install and uninstall hooks

The preparation is complete, and the rest is to load the hook into the hook linked list.

We can write two methods for calling in a proper position in the program. The Code is as follows:

// Install hook public void HookStart () {if (hMouseHook = 0) {// create HookProc instance MouseHookProcedure = new HookProc (MouseHookProc ); // set the thread hook hMouseHook = SetWindowsHookEx (2, KeyboardHookProcedure, IntPtr. zero, GetCurrentThreadId (); // if the hook fails to be set if (hMouseHook = 0) {HookStop (); throw new Exception ("SetWindowsHookEx failed. ") ;}}// uninstall the hook public void HookStop () {bool retKeyboard = true; if (hKeyboardHook! = 0) {retKeyboard = UnhookWindowsHookEx (hKeyboardHook); hKeyboardHook = 0;} if (! (RetMouse & retKeyboard) throw new Exception ("UnhookWindowsHookEx failed .");}

The key to installing and uninstalling Hooks is the SetWindowsHookEx and UnhookWindowsHookEx methods.

The SetWindowsHookEx (int idHook, HookProc lpfn, IntPtr hInstance, int threadId) function adds the hook to the hook list and describes the four parameters:

IdHookHook type, that is, to determine the type of message the hook listens to. The above code is set to 2, that is, listening to keyboard messages and being a thread hook. If it is a global hook, listening to keyboard messages should be set to 13, set the thread hook to listen to the mouse message to 7, and the global hook to listen to the mouse message to 14.

LpfnThe address pointer of the hook program. If the dwThreadId parameter is 0 or is identified by a thread created by another process, lpfn must point to the hook Child Program in the DLL. In addition, lpfn can point to a hook sub-program code of the current process. The entry address of the hook function. This function is called when the hook hooks any message.

HInstanceApplication instance handle

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.