Setwindowshookex principle (how to use hooks and hook functions of other processes)

Source: Internet
Author: User

Basic Concepts
Hook is a platform for message processing in windows. Applications can set sub-processes on the platform to monitor messages in a specified window, the monitored window can be created by other processes. When a message arrives, process it before the target window processing function. The hook mechanism allows applications to intercept and process window messages or specific events. A hook is actually a program segment for message processing. It is called by the system and mounted to the system. When a specific message is sent, the hook program captures the message before it reaches the target window, that is, the hook function gets control of the message first. In this case, the hook function can process (Change) the message, continue to transmit the message without processing it, and forcibly end the message transmission.

Operating Mechanism
1. Hook linked list and hook sub-process:
Each Hook has an associated pointer list, called a hook linked list, which is maintained by the system. The pointer to this list points to the specified callback function defined by the application procedure and called by the hook sub-process, that is, each processing sub-process of the hook. When a message associated with the specified hook type occurs, the system passes the message to the hook sub-process. Some hook sub-processes can only monitor messages, modify messages, or stop messages from being pushed forward to the next hook sub-process or target window. The recently installed hooks are placed at the beginning of the chain, and the earliest installed hooks are placed at the end, that is, the later hooks are added to obtain control.

Windows does not require that the order in which the hook program is detached must be different from that in the installation sequence. Every time a hook is detached, Windows releases the memory it occupies and updates the entire hook linked list. If the program is installed with a hook, but it is finished before the hook is uninstalled, the system will automatically uninstall the hook for it.
A hook is a callback function defined by an application. It cannot be defined as a member function of a class, but can only be defined as a common C function. It is used to monitor the system or a specific type of events. These events can be associated with a specific thread or all threads in the system.

The hook procedure must follow the following syntax:
Lresult callback hookproc
(
Int ncode,
Wparam,
Lparam
);
Hookproc is the name defined by the application.
The ncode parameter is the hook code. The hook sub-process uses this parameter to determine the task. The value of this parameter depends on the hook type. Each Hook has its own hook code feature character set.
The values of wparam and lparam parameters depend on the hook code, but their typical values contain information about sending or receiving messages.

2. Hook installation and release:
Use the API function setwindowshookex () to install the hook Program defined by an application to the hook list. The setwindowshookex function always installs the hook sub-program at the beginning of the hook chain. When a specified hook monitoring event occurs, the system calls the hook child program starting with the hook chain associated with the hook. The hook sub-process in each hook chain determines whether to pass the event to the next hook sub-process. The callnexthookex function must be called when the hook sub-process transmits an event to the next hook sub-process.

Hhook setwindowshookex (
Int idhook, // hook type, that is, the type of the message it processes
Hookproc lpfn, // address pointer of the hook sub-program. If the dwthreadid parameter is 0
// Or the ID of a thread created by another process,
// The lpfn must point to the hook program in the DLL.
// In addition, lpfn can point to a hook sub-program code of the current process.
// Hook function entry address. This function is called when the hook hooks any message.
Hinstance hmod, // handle of the application instance. ID of the Child Program that contains the lpfn
DLL.
// If dwthreadid identifies a thread created by the current process,
// And the Child Code is in the current process. hmod must be null.
// You can easily set the instance handle of the application.
DWORD dwthreadid // The identifier of the Thread associated with the installed hook program.
// If the value is 0, the hook sub-program is associated with all threads, that is, the global hook.
);

If the function succeeds, the handle of the hook sub-program is returned. If the function fails, null is returned.
The hook sub-program is associated with the thread, which means that messages sent to the thread in a hook linked list are sent to the hook sub-program at the same time and are processed by the hook sub-program first. After the hook sub-program completes message processing, if you want to continue passing the message, it must call the API function callnexthookex in another SDK to pass it, to execute the next hook program referred to by the hook linked list. When this function succeeds, the return value of the next hook process in the hook chain is returned. The type of the returned value depends on the hook type. The prototype of this function is as follows:
Lresult callnexthookex
(
Hhook HHK;
Int ncode;
Wparam;
Lparam;
);
HHK is the handle of the current hook, Which is returned by the setwindowshookex () function.
Ncode is the event Code passed to the hook process.
Wparam and lparam are the wparam values passed to the hook sub-program, and their meanings are related to the hook type.
The hook function can also directly return true to discard the message and prevent the message from being transmitted. Otherwise, other apps installed with hooks will not receive hook notifications and may produce incorrect results.
After the hook is used, unhookwindowshookex () must be used to uninstall the hook. Otherwise, it may cause trouble. The release hook is relatively simple. unhookwindowshookex () has only one parameter. The function prototype is as follows:
Unhookwindowshookex
(
Hhook HHK;
);
If the function is successful, true is returned. Otherwise, false is returned.

3. Some operating mechanisms:
In the Win16 environment, the global data of DLL is the same for every process loaded into it; but in the Win32 environment, the situation has changed, any object (including variables) created by the code in the DLL function is owned by the thread or process that calls it. When a process loads a DLL, the operating system automatically maps the DLL address to the private space of the process, that is, the virtual address space of the process, also, copy the global data of the DLL to the process space. That is to say, the global data of the same DLL owned by each process has the same name, but its values are not necessarily the same, and they do not interfere with each other.
Therefore, to share data among multiple processes in a Win32 environment, you must make necessary settings. The shared memory between processes accessing the same DLL is implemented through the memory ing file technology. You can also separate the data to be shared, place it in an independent data segment, and set the attribute of the segment to share. These variables must be assigned with initial values. Otherwise, the compiler will place the variables without initial values in a data segment called uninitialized.
# The Pragma data_seg preprocessing command is used to set the shared data segment. For example:
# Pragma data_seg ("shareddataname ")
Hhook = NULL;
# Pragma data_seg ()
All variables between # pragma data_seg ("shareddataname") and # pragma data_seg () are viewed and shared by all the processes accessing the DLL. Add a command # pragma comment (linker, "/section:. shareddataname, RWS"). Then, the data in this data section can be shared among all DLL instances. All operations on the data are performed on the same instance, instead of having a copy in the address space of each process.
When a process implicitly or explicitly calls a function in a dynamic library, the system maps the dynamic library to the virtual address space of the process (hereinafter referred to as "address space "). This makes the DLL part of a process and runs as the process and uses the stack of the process.
4. System hooks and thread hooks:
The last parameter of the setwindowshookex () function determines whether the hook is a system hook or a thread hook.
The thread hook is used to monitor the event messages of a specified thread. The thread hooks are generally within the current thread or the thread derived from the current thread.
The system hooks the event messages of all threads in the system. Because the system hooks will affect all applications in the system, the hooks must be placed in an independent dynamic link library (DLL. The system automatically maps the DLL containing the "hook callback function" to the address space of all processes affected by the hook function, which injects the DLL into those processes.
Notes:
(1) If a thread hook and a system hook are installed for the same event (such as a mouse message), the system automatically calls the thread hook and then calls the system hook.
(2) Multiple hooks can be installed for the same event message. These hooks form a hook chain. After the current hook processing is complete, the hook information should be passed to the next hook function.
(3) hooks, especially system hooks, consume message processing time and reduce system performance. You must install the hooks only when necessary and uninstall the hooks immediately after use.

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.