Use VC ++ in Windows to implement the hook Mechanism

Source: Internet
Author: User

Abstract: This article analyzes what is a hook program in windows and how to use VC ++ to implement a hook mechanism. Finally, we use a complete program that intercepts mouse information to illustrate these problems.

Key words: hook program DLL message interception

1. What is a hook.
The Windows system is based on the event-driven mechanism. To put it bluntly, the entire system is implemented through message transmission. Hook is a special message processing mechanism. It can monitor various event messages in the system or process, intercept and process messages sent to the target window. In this way, we can install custom hooks in the system to monitor the occurrence of specific events in the system and complete specific functions, such as intercepting keyboard and mouse input, and retrieving words on the screen, log monitoring.
There are many types of hooks. Each Hook can intercept and process corresponding messages. For example, a keyboard Hook can intercept keyboard messages, and a shell Hook can intercept, start, and close application messages. Hooks can be divided into thread hooks and system hooks. Thread hooks monitor event messages of specified threads, and system hooks monitor event messages of all threads in the system. Because system hooks affect all applications in the system, hook functions must be placed in an independent dynamic link library (DLL.

2. Several Key Technologies for implementing the hook mechanism.
1. For Windows Hook programs, you need to use several API functions in the SDK. The following lists the prototypes and descriptions of these functions:
Hhook setwindowshookex (INT idhook, hook_proc lpfn, hinstance hmod, DWORD dwthreadid );
Parameters are described as follows:
Idhook: hook type
Lpfn: hook processing function address
Hmod: module handle containing Hook Functions
Dwthreadid: hook monitoring thread
Function Description: A hook of the specified type is attached to the system to monitor and process specific messages.
Bool unhookwindowshookex (hhook HHK );
Function Description: The function removes the hook specified by HHK.
Lresult callnexthookex (hhook HHK, int ncode, wparam, lparam );
Function Description: The function transmits messages downward, and the next hook process intercepts the message.
2. because hook processing involves data addresses between modules and processes, it is generally integrated into a dynamic link library (DLL, there are three types of mfc dll available in VC: Regular statically linked to mfc dll (Standard static link mfc dll), regular using the shared mfc dll (Standard Dynamic Link mfc dll) and extension mfc dll (Extended mfc dll ). The first type of DLL is to link the used MFC code to the DLL during compilation. When executing the program, it does not need the support of other MFC dynamic link class libraries, but it is large; the second type of DLL is dynamically linked to the MFC class library at runtime, so it is small but dependent on the support of the MFC dynamic link class library. Both types of DLL can be used by the MFC program and Win32 program. The third type of DLL is dynamic connection, but as an extension of the MFC class library, it can only be used by the MFC program.
In addition, you need to set up a global data shared data segment to store some global variables and retain the status when the last hook message event occurred.
3. The entry and exit functions of Win32 DLL are both dllmain. This function is called whenever a process or thread loads or unmounts a DLL. Its prototype is:
Bool winapi dllmain (hinstance hinstdll, DWORD fdwreason, lpvoid lpvreserved); the first parameter indicates the DLL instance handle; the third parameter is retained; the second parameter specifies the status of the dynamic connection library currently called. It has four possible values: dll_process_attach (process loading), dll_thread_attach (thread loading), and dll_thread_detach (thread unloading), dll_process_detach (process uninstall ). In the dllmain function, you can identify the passed value of this parameter and initialize or clean the DLL according to different parameter values. In the Win32 environment, the space of all processes is independent of each other, which reduces the interaction between applications, but greatly increases the programming difficulty. When a process dynamically loads a DLL, the system automatically maps the DLL address to the private space of the process and copies the global data of the DLL to the process space, the global data values of the same DLL owned by each process are not necessarily the same. When the dll Memory is mapped to the process space, each process has its own global memory copy, and every new process that loads the DLL reinitializes this memory area, that is to say, the process can no longer share the DLL. Therefore, to share data among multiple processes in a Win32 environment, you must make necessary settings. One way is to separate the data to be shared, place it in an independent data segment, set the attribute of the segment to share, and create a DLL for Memory Sharing.

3. Use the hook mechanism to intercept the number of press times of the left and right mouse keys.
When you create a hook program, you need to integrate the hook processing into the dynamic link library. Therefore, you need to create two projects in the routine.
1. Hook Processing dynamic link library
(1) Select MFC Appwizard (DLL) to create a new project named "spy ".
(2) Select the MFC extension DLL type.
(3) create a new header file named "hook. H" and modify the Code as follows:
Extern "C" lresult callback mouseproc (INT code, wparam, lparam); // hook processing function
Extern "C" bool winapi starthook (); // start the hook function
Extern "C" bool winapi stophook (); // undo the hook function
Extern "C" int winapi getresultl (); // function used to obtain the number of left-click clicks
Extern "C" int winapi getresultr (); // you can call this function to obtain the number of times a right-click is clicked.
(4) modify the spy. cpp program code as follows:
# Include "hook. H" // include the header file hook

# Pragma data_seg ("publicdata") // defines the global data segment
Hhook = NULL; // hook handle
Hinstance pinstance = NULL; // hook module handle
Uint mouseclickl = 0; // variable that records the number of left mouse clicks
Uint mouseclickr = 0; // record the number of times you right-click
# Pragma data_seg ()

Extern "C" int apientry
Dllmain (hinstance, DWORD dwreason, lpvoid lpreserved)
{If (dwreason = dll_process_attach)
{...... // Omit some machine Generation Code
New cdynlinklibrary (spydll );
Pinstance = hinstance; // obtain the module handle
}
......;
}

Extern "C" lresult callback mouseproc (INT code, wparam, lparam) // hook processing function
{
If (Code <0) // If Code <0, call callnexthookex to return
Return callnexthookex (hhook, code, wparam, lparam );
If (wparam = wm_lbuttondown)
{Mouseclickl ++; // record the number of left mouse clicks}
If (wparam = wm_rbuttondown)
{Mouseclickr ++; // record the number of times you right-click the mouse}
Return callnexthookex (hhook, code, wparam, lparam );
}

Extern "C" bool winapi starthook () // start the hook function
{
Hhook = setwindowshookex (wh_mouse, mouseproc, pinstance, 0); // hook
If (hhook! = NULL)
Return true;
Else return false;
}

Extern "C" bool winapi stophook () // undo the hook function
{Return unhookwindowshookex (hhook); // undo hook}

Extern "C" int winapi getresultl () // returns the number of times the left mouse button is clicked
{Return mouseclickl ;}

Extern "C" int winapi getresultr () // returns the number of times the right-click operation is performed.
{Return mouseclickr ;}
  
(5) modify the spy. Def program code as follows:
Exports
Stophook @ 2
Starthook @ 1
Getresultl @ 3
Getresultr @ 4
(6) compile the project and generate the spy. dll file and the spy. Lib file.

Http://www.studa.net 2. Build applications using hooks
(1) generate an executable file (exe) project for a single document.
(2) modify the main menu in the resource and add a menu item "Monitor". There are three submenu items, namely "start", "undo", and "retrieve ".
(3) Add the spy. Lib file to the project.
(4) modify the command response functions of the "Start", "undo", and "retrieve" menu items respectively as follows:
# Include "E:/devstudio/myprojects/spy/hook. H" // The path can be different.
Void cmainframe: onmenuitem32771 () // response function of the "Start" menu item
{Starthook ();}
Void cmainframe: onmenuitem32772 () // response function of the "undo" menu item
{Stophook ();}
Void cmainframe: onmenuitem32773 () // response function for retrieving the menu item
{Int resultl = getresultl ();
Int resultr = getresultr ();
Char buffer [80];
Wsprintf (buffer, "during the program running, you click % d with the left mouse button and right click % d! ", Resultl, resultr );
: MessageBox (this-> m_hwnd, buffer, "message", mb_ OK );
}
Compile the project and put spy. dll in the generated executable file directory to run the program. During running, select the "Start" menu item in the "monitoring" menu to start the hook and monitor the mouse activity. Select the "undo" menu item to undo the hook; select the "retrieve" menu item, and the program reports the number of times the user clicks the left mouse button and right-click during monitoring.
The above programs run successfully in Windows 98, Visual C ++ 5.0, and 6.0 environments. The implementation of other types of hook programs is similar to this.

References
[1] Scott sanfield Ralph arvesen. VC ++ developer guide. Publishing House of Electronics Industry
[2] He chengshi. Win32 global hook in vc5

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.