Hook Application Example 2

Source: Internet
Author: User
I. Introduction
The essence of a hook is a program used to process system messages. It is mounted to the system through system calls. There are many types of hooks. Each Hook can intercept and process the corresponding message. Each time a specific message is sent, the hook program intercepts the message before reaching the target window to gain control of the message. In this case, the hook function can process intercepted messages and even forcibly End message transmission. This is a bit similar to the pretranslatemessage function in MFC. The difference is that this function can only be used to intercept messages in the current process, but is powerless to system messages.
Ii. Win32 system hook implementation
Each type of Hook is maintained by the system. The recently installed hook is at the beginning of the chain and has the highest priority. The first installed hook is at the end of the chain. To implement a Win32 system hook, you must first call the SDK's API function setwindowshookex to install the hook function. Its prototype is:
Hhook setwindowshookex (INT idhook,
Hookproc lpfn,
Hinstance hmod,
DWORD dwthreadid );
Among them, the first parameter is the hook type, commonly used wh_mouse, wh_keyboard, wh_getmessage, and so on; The second parameter is the address of the hook function, call this function when the hook hooks any message. The third parameter is the handle of the module where the hook function is located; the fourth parameter is the ID of the hook-related function used to specify the thread to which the hook is to be hooked. If the value is 0, the system will intercept messages of the entire system. This is a global hook. If a specific thread is specified, it is a dedicated hook of the thread.
Global hook functions must be included in DLL (Dynamic Link Library), while thread-specific hooks can be included in executable files. After processing the message, the hook function that obtains control can call the callnexthookex API function in another SDK to continue to transmit the message. You can also discard the message by directly returning true to prevent delivery of the message.
When using global hook functions, you need to use dll as the carrier. There are three forms of mfc dll in vc6 to choose from, that is, 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.
Iii. Win32 DLL
The entry and exit functions of Win32 DLL are both dllmain, which is different from Win16 DLL. 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.
Iv. Global Data Sharing
You can use # pragma data_seg to create a new data segment and define shared data. The specific format is:
# Pragma data_seg ("shareddata ")
Hwnd sharedwnd = NULL; // share data
# Pragma data_seg ()
All variables declared between data_seg pragmas statements are in the shareddata segment. Defining only one data segment can not achieve the purpose of sharing data, but also tell the compiler the attributes of this segment, there are two ways to achieve this (the effect is the same ), one way is in. add the following statement to the def file:
Setctions
Shareddata read write shared
Another method is to add the following statement to the project setting link option:
/Section: shareddata, RWS
V. Example of a mouse hook Program
The global hook function is used in this example. The program consists of the executable program mousedemo and the dynamic Connection Library mousehook. First, compile the MFC extended dynamic Connection Library mousehook. dll:
(1) Select MFC Appwizard (DLL) to create the project mousehook;
(2) Select the MFC extension DLL (MFC extension DLL) type;
(3) Use "New…" in the addtoproject sub-menu of the Project menu... "Add the header file mousehook. h.
(4) create a hook class in the header file:
Class afx_ext_class cmousehook: Public cobject
{
Public:
Cmousehook (); // constructor of the hook class
~ Cmousehook (); // hook class destructor
Bool starthook (hwnd); // install the hook function
Bool stophook (); // uninstall the hook function
};
(5) Add the # include "mousehook. H" Statement to the mousehook. cpp file;
(6) add global shared data variables:
# 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
Hhook glhhook = NULL; // installed mouse hook handle
Hinstance glhinstance = NULL; // DLL instance handle
# Pragma data_seg ()
(7) define the segment attribute in the def file:
Sections
Mydata read write shared
(8) Add the statement for saving the DLL instance handle to the dllmain function of the main file mousehook. cpp:
Extern "C" int apientry
Dllmain (hinstance, DWORD dwreason, lpvoid lpreserved)
{
Unreferenced_parameter (lpreserved );
If (dwreason = dll_process_attach)
{
If (! Afxinitextensionmodule (mousehookdll, hinstance ))
Return 0;
New cdynlinklibrary (mousehookdll );
Glhinstance = hinstance; // insert and save the DLL instance handle
}
Else if (dwreason = dll_process_detach)
{
Afxtermextensionmodule (mousehookdll );
}
Return 1; // OK
}
The most important part of this function is to call afxinitextensionmodule (), which initializes the DLL so that it works correctly in the MFC framework. It must be passed to the DLL instance handle of dllmain () and the afx_extension_module structure. The structure contains useful information for MFC.
(9) Implementation of member functions of class cmousehook:
Cmousehook: cmousehook () // class Constructor
{
}
Cmousehook ::~ Cmousehook () // class destructor
{
Stophook ();
}
Bool cmousehook: starthook (hwnd) // install the hook and set the handle for receiving the display window
{
Bool bresult = false;
Glhhook = setwindowshookex (wh_mouse, mouseproc, glhinstance, 0 );
If (glhhook! = NULL)
Bresult = true;
Glhdisplaywnd = hwnd; // set the handle to display the title edit box of the target window.
Return bresult;
}
Bool cmousehook: stophook () // uninstall the hook
{
Bool bresult = false;
If (glhhook)
{
Bresult = unhookwindowshookex (glhhook );
If (bresult)
{
Glhprevtarwnd = NULL;
Glhdisplaywnd = NULL; // clear the variable
Glhhook = NULL;
}
}
Return bresult;
}
(10) Implementation of Hook Functions
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
}
}
Return callnexthookex (glhhook, ncode, wparam, lparam); // continue to pass the message
}
After compilation, you can obtain the dynamic Connection Library mousehook. dll and the mousehook. Lib used in the link for the mouse hook required for running.
Vi. Integration
Next we will create a new hook executable program that calls the mouse hook to dynamically connect to the database:
(1) Use the Appwizard (exe) of MFC to create the project mousedemo;
(2) Select "dialog-based application" and save the remaining steps;
(3) add an edit box idc_edit1 to the dialog box;
(4) Add the inclusion statement for mousehook. h to mousedemo. h: # include "mousehook. H ";
(5) Add the private data member cmousehook m_hook in the cmousedemodlg. H class definition;
(6) add the following after "Todo comment" of the oninitdialog function:
Cwnd * pwnd = getdlgitem (idc_edit1); // get the class pointer of the edit box
M_hook.starthook (pwnd-> getsafehwnd (); // obtain the window handle in the editing box and install the hook.
(7) link the dll library to add mousehook. lib to the project setting link tag;
(8) Copy mousehook. h and mousehook. lib to the mousedemo project directory and mousehook. DLL to the DEBUG directory. Compile and execute the program. When the mouse slides over the window, the title of the window is displayed in the edit box.
Conclusion:
The system hook has very powerful functions. Through this technology, almost all windows
System messages are intercepted, monitored, and processed. This technology can be widely used in a variety of software, especially the need
Software that monitors the system, such as monitoring and automatic recording. This program only intercepts mouse messages,
You can also apply this technology to the keyboard, port, and other functions in the Win32 environment.

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.