Hook programming skills based on Visual C ++

xiaoxiao2021-03-06  185

Hook outline

The hook is a point (Point) of the Windows message processing mechanism. The application can intercept the Window message or some other particular events by hook mechanisms. Similar to the DOS interrupt interception process, the application can set multiple hook functions on the hook, which make up a pointer list (hook chain table) associated with the hook. When the message monitored by the hook appears, Windows first sent it to the first hook function pointed to by the call list, and the hook function will monitor, modify, and control the message according to its respective functions, and after the processing is completed. Pass the message to the next hook function until the end of the hook linked list. After the hook function is handed over, the intercepted message will eventually return to the window handler. Although the hook function of the hook will slightly add the operating efficiency of the system, but in many cases, the filter processing of the hook can complete the special functions that can be completed by other methods.

It can be seen that the essence of the hook is a function to handle system messages or specific events, and hang it into the system through system calls. There are many types of hooks, and each hook is responsible for intercepting and handling corresponding messages. The hook mechanism allows the application to intercept and process messages or specific events sent to the specified window, which can be created in this process can be created in this process. After the specific message is issued, the hook program has the right to control before the destination window. At this time, the hook function can be performed in addition to the intercepted message, and even the continued transmission of the message can be forcible.

For multiple hooks, the recently installed hook will be placed in the beginning of the hook chain, the earliest installed hook is placed in the final, when the message monitored, the operating system calls the first hook function at the beginning of the latch. Treatment, that is, said the last hook gives priority to obtain control. The hook function mentioned here must be a callback function, and cannot be defined as a class member function, which can only be a normal C function, such as:

LResult Callback HookProc (int Ncode, WPARAM WPARAM, LPARAM LPARAM);

Thread topical hook and system global hook

The hook is divided into two major classes of the system global hook and threads depending on the scope of the message monitoring, wherein the threaded partial hook can only monitor a specified thread in this process, and the global hook can run under the current system. All threads are monitored. Obviously, thread hooks can be seen as a subset of global hooks, although the global hook is powerful but also is more cumbersome: The implementation of its hook functions must be packaged in a separate dynamic link library to be associated by various associations. The application is used.

Although the thread is not required to be placed in a dynamic link library, the recommended approach is still in the dynamic link library. Such treats not only enable the hook to be accessed by multiple processes within the system, but also can be called directly in the system. For a hook accessible only a single process, it is also possible to place its hook processing in the same thread of the mounting hook. Hook installation and uninstall

The system is intercepted by calling the hook function at the beginning of the hook list, so the chain of the recovery function is placed in the chain of the hook linked list when setting the hook, and the operating system will be called first. The function setWindowsHooKex () is responsible for placing the callback function in the start position of the hook list. Setwindowshookex () function prototype declaration is:

HHOOK SETWINDOWSHOKEX (Int IDHOK; HookProc LPFN; Hinstance Hmod; DWORD DWTHREADID);

Among them, the parameter IDHOOK specifies the type of hook, and the types that can be used are 13:

The "hook" WH_CallWndProcret message "hook" WH_CALLWndProcret message has been processed before the message to the specified window "WH_Debug error" hook "WH_Debug error" hook "WH_ForeGroundIdle front desk" hook "WH_GetMessage receives message delivery" hook "WH_JOURNALPLAYBACK before playback by WH_JOURNALRECORD" hook "incoming message record of WH_JOURNALRECORD incoming message record" hook "WH_KEYBOARD keyboard message" hook "WH_MOUSE mouse messages" hook "WH_MSGFILTER dialog box, message box, menu, or scroll bar to enter the message" hook "WH_SHELL The housing "hook" WH_SYSMSGFILTER system message "hook" parameter LPFN is a pointer to the hook function, that is, the first address of the callback function; the parameter hmod identifies the handle of the module of the hook processing function; the parameter dWThreadID specifies the monitored thread, if it is clear The ID specified that a thread only monitors the thread. At this time, the hook is a thread hook; if the parameter is set to 0, it means that this hook is a global hook for all threads of the monitoring system. This function will return a hook handle after execution.

After the setWindowsHooKex () function completes the installation of the hook, if the monitored event occurs, the system will immediately call the hook function at the beginning of the corresponding hook list, and each hook function should consider whether it needs to put events when processed. Pass it to the next hook handler. If you need to pass, you want to call the function callnesthookex (). Although it is theoretically do not call CallNESTHOKEX (), it is also strong in actual use, it is strongly recommended whether or not the event transfer must be called at the final call, otherwise some unpredictable systems will be Behavior or system lock. This function will return the address of the next hook processing in the hook table, as for the specific return value type, depending on the set hook type. The function prototype of CallNexthooKex () is:

LResult CallnexthooKex (HHOOK HHK; INT NCODE; WPARAM WPARAM; LPARAM LPARAM);

Where the parameter hHK is the current hook handle returned by the setWindowsHookex () function; the parameter ncode is the event code for the hook process; the parameters WPARAM and LPARAM are the parameter value of the hook processing function, and the specific meaning of the specifically the same hook type related.

Since the installation of the hook has a certain impact on the performance of the system, it should be unloaded in time after the hook is used to release its resources. The function of the release hook is unHookWindowsHooKex (), which is more simple to have a parameter for specifying the hook handle returned by the setWindowsHooKex () function. The prototype declaration is as follows:

Bool UnHookWindowsHookex (HHOOK HHK);

Use a mouse hook

Since the system global hook is functionally covered with thread local hooks, its actual use range is much more wide than the wires. This section also focuses on the use of system global hooks.

Mouse hooks are more commonly used in hooks and a relatively simple type of hook. The application examples given below will capture the window header of the current window of the mouse by installing the mouse global hook. Since this routine uses a global hook, first construct a carrier-dynamic link library of global hooks. Considering the difference in Win32 DLL and Win16 DLL, you must share data between multiple processes in a Win32 environment, you must take some steps to extract the data to be shared to a separate data segment and set its property through the DEF file. Sharing for reading and writing:

#pragma data_seg ("mydata") hwnd glhprevtarwnd = null; // The window handle of the last mouse is hwnd glhdisplayWnd = null; // Display the handle of the target window title edit box HWND GLHHOOK = NULL; // Installed Mouse hook handle Hinstance Glhinstance = NULL; // DLL Equation Handle #pragma Data_SEG () ... Sections // DEF file Settings Data TestData to read and write TestData Read Write Shared After completing the above preparation, STARTHOOK is output in dynamic library output ) The SETWINDOWSHOKEX () function completes the installation of 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 hWnd) {BOOL result = FALSE; // mounting hook glhHook = (HWND) SetWindowsHookEx (WH_MOUSE, MouseProc, glhInstance, 0); if (! GlhHook = NULL) result = TRUE; glhDisplayWnd = hWnd; // Set the handle of the display target window title edit box Return Result;}

After the mouse hook is installed, the mouse message emitted by any mouse action within the system must pass the interception filtering of the hook function mouseproc (). The process performed here is by getting the window handle under the location of the current mouse, and further get the window title. After the processing is completed, call the callNextHooKex () function to pass this event to the next hook function in the hook list:

LRESULT WINAPI MouseProc (int nCode, WPARAM wParam, LPARAM lParam) {LPMOUSEHOOKSTRUCT pMouseHook = (MOUSEHOOKSTRUCT FAR *) lParam; if (nCode> = 0) {HWND glhTargetWnd = pMouseHook-> hwnd; // get the target window handle HWND ParentWnd = glhTargetWnd ; while (ParentWnd = NULL!) {glhTargetWnd = ParentWnd; ParentWnd = GetParent (glhTargetWnd); // get the main application window handle} if (glhTargetWnd = glhPrevTarWnd!) {char szCaption [100]; GetWindowText (glhTargetWnd, szCaption, 100 ); // get title of the window if (IsWindow (glhDisplayWnd)) SendMessage (glhDisplayWnd, WM_SETTEXT, 0, (LPARAM) (LPCTSTR) szCaption); glhPrevTarWnd = glhTargetWnd; //}} // save the target window to pass on the message return CallNextHookEx ((HHOOK) GLHHHOK, NCODE, WPARAM, LPARAM;

This dynamic link library also provides an output function stophook (), and the calling program is uninstalled to the previously loaded hook by calling the call to this function. In this function is output through the UnhookWindowsHookEx () function to unload the specified hook: BOOL CMouseHook :: StopHook () {BOOL result = FALSE; if (glhHook) {result = UnhookWindowsHookEx ((HHOOK) glhHook); // unloading hook IF (result) glhdisplayWnd = GLHPREVTARWND = GLHHHHOOK = NULL;} Return Result;}

By compiling, the link can get a dynamic link library for the mouse global hook. After the call has been called, the interception processing of the mouse message in all threads in the current system can be implemented. After the hook dynamic link library is loaded into the process, simply call the output function StartHook () to install the global hook to intercept the mouse message, call the output function Stophook () uninstall the hook before the call program exits.

Use keyboard hooks

The keyboard hook is the same as the mouse hook, is also a class of more common hooks. Moreover, in general, the use of the keyboard hook and the use of the mouse hook is also more similar, and the use of the keyboard hook will be described by a program instance, in which the keyboard global hook is recorded by setting the keyboard global hook. And save the characters to the file by date.

Since the system global hooks used in this routine, it consists of both the calling program and the dynamic link library program. The dynamic link library program provides two output functions installlaunchev () and Uninstall (), which are used for installation and uninstalling of keyboard hooks:

DllExport void WINAPI InstallLaunchEv () {glhHook = (HHOOK) SetWindowsHookEx (WH_KEYBOARD, (HOOKPROC) LauncherHook, theApp.m_hInstance, 0); // install the keyboard hook} DllExport void WINAPI UnInstall () {if (glhHook) {BOOL result = UnhookWindowsHookEx ((HHOOK) GLHHOOK; // Unload hooks IF (Result) Glhhook = NULL;}}

In the hook installation function, the keyboard hook function launcherhook () is set by SetWindowsHookex (). This hook function will be called after the keyboard event occurs, and the captured character is saved to the file by savelog () function:

LRESULT CALLBACK LauncherHook (int nCode, WPARAM wParam, LPARAM lParam) {// event is passed to the next keyboard hook function LRESULT Result = CallNextHookEx (glhHook, nCode, wParam, lParam); if (nCode == HC_ACTION) // keyboard handling Action {if (lparam & 0x80000000) // Save the keyboard action to file {char C [1]; C [0] = wparam; savelog (c); if (c [0] == 13) {C [0] = SAVELOG (C);}}} Return Result;}

As for the calling program, it is very simple, just after the program starts running and calls the hook setting function and the hook uninstall function provided by the dynamic link library before the program exit. There are many types of hooks, and the mouse hooks and keyboard hooks given in the previous areas can also be seen very similar. Usually, the dynamic link library as a hook carrier is provided to provide two necessary output functions - hook mount functions and hook unload functions. In the hook installation function, the corresponding hook function is set for different types of hooks in the hook installation function, and the substantive work is mainly completed in the hook function, and the specific condition should be adjusted to the type of hook and the function to be completed. In the hook uninstallation function, it is mainly called the unHookWindowsHooKex (), and supplemented with the necessary protective code.

Source: Tianji Software Channel

转载请注明原文地址:https://www.9cbs.com/read-128471.html

New Post(0)