Hook Programming Skills Based on Visual C ++

Source: Internet
Author: User

Summary: This article mainly discusses the special windows programming mechanism, such as hook, and provides specific implementation methods for mouse hook and keyboard hook.

  Keywords: Hook; mouse hook; Visual C ++

  Hook Overview

Hook is a key point of Windows message processing mechanism ). Applications can intercept and process window messages or other specific events through the hook mechanism. Similar to the DOS interrupt interception processing mechanism, an application can set multiple hook functions on the hook to form a list of pointers associated with the hook function (Hook linked list ). When a message monitored by a hook appears, Windows sends it to the first hook function pointed to in the linked list, the hook function monitors, modifies, and controls messages based on their respective functions, and passes messages to the next hook function after processing is completed until it reaches the end of the hook list. After the hook function gives control, the intercepted messages are finally returned to the window handler. Although the hook function filters messages, it will slightly affect the system operation efficiency, however, in many cases, you can use hooks to filter messages and perform special functions that cannot be completed by other methods.

It can be seen that the essence of a hook is a function used to process system messages or specific events. It is mounted to the system through system calls. There are many types of hooks, each of which is responsible for intercepting and processing the corresponding messages. The hook mechanism allows an application to intercept and process messages or specific events sent to a specified window. The monitored window can be created by other processes in the current process. After a specific message is sent and before reaching the target window, the hook program has control over it. In this case, the hook function can not only process intercepted messages, you can even force termination of message transmission.

For the installation of multiple hooks, the recently installed hooks will be placed at the beginning of the hook chain, and the earliest installed hooks will be placed at the end. When the hook monitoring message appears, the operating system calls the first hook function at the beginning of the linked list for processing. That is to say, the last hook is preferentially controlled. The hook function mentioned here must be a callback function and cannot be defined as a class member function. It can only be a common C function, for example:

Lresult callback hookproc (INT ncode, wparam, lparam );

  Local hooks of threads and global hooks OF THE SYSTEM

Hooks are divided into two categories: system global hooks and Thread Local hooks based on their different message monitoring scopes. Thread Local hooks can only monitor a specified thread in the process, the global Hook can monitor all threads running in the current system. Obviously, thread hooks can be considered as a subset of global hooks. Although global hooks are powerful, they are also cumbersome to implement at the same time: the implementation of the hook function must be encapsulated in an independent dynamic link library before it can be used by various associated applications.

Although local hooks of threads do not require them to be placed in the dynamic link library like global hooks of the system, it is recommended to put them in the dynamic link library for implementation. This processing not only enables the hook to be accessed by multiple processes in the system, but also can be directly called in the system. For a hook that is only accessible by a single process, you can also put the hook processing process in the same thread where the hook is installed.

 

Hook installation and uninstallation

The system intercepts messages by calling the hook function at the beginning of the hook list. Therefore, you must place the callback function at the beginning of the hook list, the operating system will make it called first. The setwindowshookex () function is used to place the callback function at the starting position of the hook linked list. The prototype declaration of setwindowshookex () function is as follows:

Hhook setwindowshookex (INT idhook; hookproc lpfn; hinstance hmod; DWORD dwthreadid );

The idhook parameter specifies the hook type. The following types can be used:

The "Hook" before the wh_callwndproc system sends messages to the specified window"
The "hook" that the wh_callwndprocret message has been processed in the window"
Wh_cbt "hook" based on computer training"
Wh_debug error "hook"
Wh_foregroundidle foreground idle window "Hook"
Wh_getmessage: "Hook" for receiving message delivery"
Wh_journalplayback plays back the input messages previously recorded through the wh_journalrecord "hook"
Wh_journalrecord: "Hook"
Wh_keyboard Keyboard Message "hook"
Wh_mouse mouse message "Hook"
Enter the message "Hook" in the wh_msgfilter dialog box, message box, menu, or scroll bar"
Wh_shell shell "hook"
Wh_sysmsgfilter system message "hook"

The lpfn parameter is the pointer to the hook function, that is, the first address of the callback function. The hmod parameter identifies the handle of the module where the hook processing function is located. The dwthreadid parameter specifies the thread to be monitored, if the ID of a thread is explicitly specified, only the thread is monitored. The hook is a thread hook. If this parameter is set to 0, indicates that this hook is a global hook that monitors all threads of the system. After this function is executed, a hook handle is returned.

After the setwindowshookex () function is installed on the hook, if a monitored event occurs, the system immediately calls the hook function located at the beginning of the corresponding hook list for processing, when processing each hook function, consider whether to pass the event to the next hook processing function. If you want to pass the call, call the callnesthookex () function (). Although theoretically not calling callnesthookex () is not an error, we strongly recommend that you call callnexthookex () at the end of the process, whether or not you need to transfer events (), otherwise, unexpected system behaviors or system locks may occur. This function returns the address of the next hook processing process in the hook linked list. The specific return value type depends on the set hook type. Callnexthookex (
) Function prototype:

Lresult callnexthookex (hhook HHK; int ncode; wparam; lparam );

The HHK parameter is the current hook handle returned by the setwindowshookex () function. The ncode parameter is the event Code passed to the hook process. The wparam and lparam parameters are the parameter values passed to the hook processing function, the specific meaning is related to the set hook type.

Because the installation of hooks has a certain impact on the system performance, you should promptly uninstall the hooks after they are used to release their resources. The function for releasing a hook is unhookwindowshookex (). This function has only one parameter to specify the hook handle returned by the setwindowshookex () function. The prototype declaration is as follows:

Bool unhookwindowshookex (hhook HHK );

  Use mouse hooks

Because the system global hook function completely covers the Thread Local hook, its actual use range is much wider than that of the Thread Local hook. This section also focuses on the use of global system hooks.

Mouse hooks are common and easy to use hooks. The following example uses the Global hook to capture the title of the current window. Because the global hook is used in this routine, we first construct the dynamic link library, the carrier of the global hook. Considering the differences between Win32 DLL and Win16 DLL, to share data among multiple processes in a Win32 environment, some measures must be taken to extract the data to be shared to an independent data segment, and set its attribute to read/write sharing through the def file:

# Pragma data_seg ("mydata ")
Hwnd glhprevtarwnd = NULL; // handle of the window pointed by the last mouse
Hwnd glhdisplaywnd = NULL; // display the handle of the title edit box in the target window
Hwnd glhhook = NULL; // installed mouse hook handle
Hinstance glhinstance = NULL; // DLL instance handle
# Pragma data_seg ()
......
Sections // set the data segment testdata to read/write sharing in the def File
Testdata read write shared

After completing the preceding preparations, call the setwindowshookex () function in the dynamic library output function starthook () to install the global mouse hook. Set the mouse hook function to mouseproc (), the hook handle returned by the installation function is saved in the variable glhhook:

Bool cmousehook: starthook (hwnd)
{
Bool result = false;
// Install the hook
Glhhook = (hwnd) setwindowshookex (wh_mouse, mouseproc, glhinstance, 0 );
If (glhhook! = NULL)
Result = true;
Glhdisplaywnd = hwnd; // set the handle to display the title edit box of the target window.
Return result;
}

After the mouse hook is installed, the mouse messages sent by any mouse action in the system must be intercepted and filtered by the hook function mouseproc. The processing here is to obtain the window handle at the position of the current mouse and further obtain the window title. After processing, call the callnexthookex () function to pass the event to the next hook function in the hook list:

Lresult winapi mouseproc (INT ncode, wparam, lparam)
{
Lpmousehookstruct pmousehook = (mousehookstruct far *) lparam;
If (ncode> = 0 ){
Hwnd glhtargetwnd = pmousehook-> hwnd; // retrieve the target window handle
Hwnd parentwnd = glhtargetwnd;
While (parentwnd! = NULL ){
Glhtargetwnd = parentwnd;
Parentwnd = getparent (glhtargetwnd); // retrieves the handle of the main application window
}
If (glhtargetwnd! = Glhprevtarwnd ){
Char szcaption [100];
Getwindowtext (glhtargetwnd, szcaption, 100); // obtain the title of the target window.
If (iswindow (glhdisplaywnd ))
Sendmessage (glhdisplaywnd, wm_settext, 0, (lparam) (lpctstr) szcaption );
Glhprevtarwnd = glhtargetwnd; // Save the target window
}
}
// Continue message transmission
Return callnexthookex (hhook) glhhook, ncode, wparam, lparam );
}

This dynamic link library also provides an output function stophook (), which is called by the calling program to uninstall the previously loaded hook. In this output function, the unhookwindowshookex () function is used to uninstall the specified HOOK:

Bool cmousehook: stophook ()
{
Bool result = false;
If (glhhook ){
Result = unhookwindowshookex (hhook) glhhook); // uninstall the hook.
If (result)
Glhdisplaywnd = glhprevtarwnd = glhhook = NULL;
}
Return result;
}

By compiling and linking, you can obtain a dynamic link library for the global mouse hook. After the calling program calls it, You can intercept and process mouse messages in all threads of the current system. After the hook dynamically links the Library to the process, you only need to call the output function starthook () to install the global hook to intercept and filter mouse messages. Before the program exits, call the output function stophook () uninstall the hook.

Address: http://www.yesky.com/325/1826325.shtml

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.