Windows hook mechanism detailed _c language

Source: Internet
Author: User

First, overview:

As anyone who understands Windows programming knows, Windows System programs run on the basis of messaging mechanisms, and almost all program activity is driven by messages. The hook mechanism can be regarded as a relay station of a message, and the control system sends out the processing and transmission of messages. With hooks, we can intercept messages that the system sends to the application and, after processing, decide whether to send the message to the next application. with this feature of hooks, we can create a monitoring program that collects and controls the messages sent by the system.

Second, the development of Windows Hook Program

A Windows Hook program needs several API functions in the SDK. The following is a list of the prototypes and descriptions of these functions:

Hhook SetWindowsHookEx (int idhook, Hook_proc lpfn, hinstance Hmod,dword);

Parameter description:
Idhook: Type of hook
LPFN: Hook processing function address
Hmod: A module handle containing a hook function
dwThreadID: Hook's Monitor thread

Function Description:
The function hangs a hook on the system that is specified by Idhook, monitoring and processing the specific message.

BOOL UnhookWindowsHookEx (Hhook hhk);

Function Description: The function will undo the hook specified by HHK.

Lresult CallNextHookEx (hhook hhk, int ncode, WPARAM WPARAM, LPARAM LPARAM);

Function Description: The function passes the message down, and the next hook processing intercepts the message.

Since the hook processing involves the data address problem between the module and the process, the general processing is to integrate the hook into a dynamic link library (DLL), and set up a global data sharing data segment to store some global variables and keep the state of the last Hook message event. global shared data segments can be defined in the following format:

#pragma data_seg ("Publicdata")
hhook hhook=null//Global shared Data
#pragma data_seg ()

In the sample program included with this article, we demonstrated how to develop a mouse hook (wh_mouse) program. This program monitors the Windows system's mouse message, during which the program can click the left mouse button for the user. Other types of hook programs are written in a similar style to the sample program.

The establishment of example program and code analysis

As mentioned above, the hook processing needs to be integrated into the dynamic link library to create the hooks, so you need to build two project in the routine.

1, Establish hook processing dynamic link library:

(1) Select MFC AppWizard (DLL) to create a new project named "Spy";

(2) Select MFC Extension DLL type

(3) Create a new header file, named "Hook.h", and modify its code as follows

extern "C" lresult CALLBACK mouseproc (int code,
WPARAM wparam,lparam LPARAM);//Hook handler function
extern "C" BOOL WINAPI Star Thook (); Start hook function
extern "C" BOOL WINAPI Stophook ();//undo hook function
extern "c" int WINAPI GetResult ();//Get a function of the number of mouse clicks

(4) Modify the Spy.cpp file code as follows (bold part to add content)

#include "stdafx.h" #include <afxdllx.h> #include "spyhook.h" ...//omit part of machine generated code #pragma data_seg ("publicdata")// Define global data segments Hhook Hhook=null; Hook handle hinstance pinstance=null; Hook module handle UINT mouseclick=0; The variable that records the number of mouse clicks #pragma data_seg () ...//omit part of the machine generated code extern "C" int apientry DllMain (hinstance hinstance, DWORD Dwreason, Lpvoi D lpreserved) {if (Dwreason = = Dll_process_attach) {...//omit part of machine generate code new CDynLinkLibrary (Spydll); pinstance=hinstance;//Fetch Module handle} else if (Dwreason = Dll_process_detach) {TRACE0 ("SPY.
DLL terminating!\n ");
AfxTermExtensionModule (Spydll); 
return 1; extern "C" Lresult CALLBACK mouseproc (int code,wparam WPARAM, LPARAM LPARAM)//Hook handler function {if (Code < 0)//if code<0, direct
Call CallNextHookEx returns return CallNextHookEx (Hhook, Code, WParam, LParam);
if (Wparam==wm_lbuttondown) {mouseclick++;//record number of mouse clicks} return CallNextHookEx (Hhook, Code, Wparam,lparam); extern "C" BOOL WINAPI Starthook ()//start hook function {Hhook=setwindowshookex (wh_mouse,mouseproc,pinstance,0);//hook-up child if (hhook! =NULL) return TRUE;
else return FALSE; extern "C" BOOL WINAPI Stophook ()//undo hook function {return UnhookWindowsHookEx (hhook);//Undo Hook} extern "C" int WINAPI GetResult

 ()//Returns the number of mouse clicks {return mouseclick;}

(5) Modify the Spy.def file as follows

LIBRARY "SPY"
DEs cription ' SPY Windows Dynamic Link Library '
exports
starthook
@1 stophook @2 GetResult @3

(6) Compiling project, generating Spy.dll files and Spy.Lib files

2, establish the application using hooks

Project to generate a single document executable (EXE)
Modify the main menu in the resource, add a menu item "Monitor", there are three submenu items, respectively "start", "undo", "Remove"
Add Spy.Lib and Hook.h files to project
Modify the command response function for startup, Undo, and Fetch menu items, respectively, as follows:

#include "hook.h" ...
//Omit part of machine generate code
void Cmainframe::onstartspy ()///Start menu item's response function
{starthook ();
}

void Cmainframe::onreleasespy ()//Undo menu Item Response function
{stophook ();
}

The response function of the void Cmainframe::onget ()//"Fetch" menu item
{int Result=getresult ();
Char buffer[40];
wsprintf (Buffer, "during the program run, you have a mouse click%d times", result);
:: MessageBox (This->m_hwnd,buffer, "message", MB_OK); 
}

Compile this project and put the Spy.dll in the directory of the generated executable file to run the program. At run time, select the "Start" menu item in the "Monitor" menu, the hook will start to work, monitor mouse activity, select the "Undo" menu item, the system will revoke the hook, select the "Remove" menu item, the program will report during the monitoring, the user clicks the left mouse button number.

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.