Compiling of Windows hooks

Source: Internet
Author: User
Windows hooks are compiled using DLL. At the upper layer, hooks are required to monitor other applications. Program Or system activity applications. In the lower layer, hooks are the points in Windows message transmission,
The function is injected or appended based on this path to filter messages of Certain types to reach the destination. Once these messages are captured, they can be modified, recorded, or discarded. The function itself is called
Filter. These filters are categorized by the type of the event being filtered. When a filter function is attached to a hook, it is called "sethook ". It must be set sometimes.
Multiple hooks of the same type. To handle this situation, Windows records the filtering of function chains. The recently added filter function is the first function in the chain. Therefore, it has the opportunity
Filter any message traffic. Then, this function executes its work and sends the message to the next hook process in the chain. The latter gives up the message completely. The following lists the types of wondows hooks:
Wh_callwndproc monitors all Windows messages before a message is sent to its target window routine
Wh_callwndprocret
Monitor messages that have been processed by the target Windows routine
Wh_cbt monitors messages used by computer-base-training applications
Wh_debug
Auxiliary debugging of other Hook Functions
Wh_getmessage monitors Windows messages delivered to message queues
Wh_journalplayback
Deliver messages previously processed by the wh_journalrecord exception branch routine
Wh_journalrecord
Record the input messages delivered to the system message queue
Wh_keyboard monitors keyboard Activity
Wh_keyboard_ll
Monitor low-layer keyboard input events (for Windows 2000/XP only)
Wh_mouse monitoring mouse messages
Wh_mouse_ll
Monitor low-level mouse input events (Windows 2000/XP only)
Wh_msgfilter
Monitor messages generated as the result of an event input in a dialog box, message box, menu, or scroll bar
Wh_shell
Receive Event Notifications that make sense to shell applications
Wh_sysmsgfilter
Similar to wh_msgfilter, it monitors messages generated as the result of an event input in a dialog box, message box, menu, or scroll bar. However, wh_sysmsgfilter
Monitor these messages for all active applications
Now I want to explain the setwindowshookex function.
To set a hook, you must call the setwindowshookex function. The prototype is as follows:
Hhook
Setwindowshookex (INT idhook, hookproc lpfn, hinstance hmod, DWORD dwthreadid)
The first idhook parameter represents a constant, which identifies the type of the hook to be set. The second parameter lpfn points to the hookproc type pointer of a function. Third parameter hmod
Hinstance of the module that contains the filter function. The fourth parameter is the thread ID. The return value is a hook handle. If the function fails, the return value is null. You need to call the getlasterror function,
To determine the cause of the failure.
Unhookwindowshookex Function
If a Windows Hook is set for the application, remove a hook from the hook chain before the program is terminated. This is implemented through the unhookwindowshookex function. The prototype is as follows:
Bool unhookwindowshookex (hhook)
Callnexthook Function
After a filter function is set for a given hook type, the filter function is placed in the chain header of the hook type filter function. After the filter function completes its task, you can use the callnexthook function to call the chain
The next filter function. If you do not want to continue processing, for example, if you have compiled a keyboard hook and want to discard a key, do not call this function. However, if you simply record an event and want the message
The application needs to call the callnexthook function after processing the message. Otherwise, other messages will not be processed. If this type of Hook does not have other filter functions, Windows will pass the message to the appropriate message queue.
The following is a simple example to illustrate the use of hooks. We will compile a keyboard hook program. In this example, all the keys pressing the F1 key will be captured, after you are familiar with it, you can try to capture Windows messages in message queues. This is very useful for writing plug-ins. Of course, some messages are customized in programs, however, you can still capture some messages through a write technique. This is a post.
First, create a DLL that contains the filter function for the keyboard hook and create a common DLL named keybdhook in the project. Open the keybdhook. h file and add some declarations before the ckeybdhookapp class declaration:
# Define exported_dll_function _ declspec (dllexport) _ stdcall // provides a simple way to export functions with the _ stdcall call Mechanism
Lresult _ stdcall kbdhookproc (INT ncode, wparam, lparam); // The actual filter function
Declare some global variables in keybdhook. cpp as follows:
# Pragma data_seg (". shardat ")
Static hwnd
Ghwndmain = 0;
Static hhook
Ghkeyhook = NULL;
# Pragma data_seg ()
Hiinstance
Ghinstance = 0;
Hookproc glpfnhookproc = 0;
Well, the implementation of the kbdhookproc function is as follows:
Lresult exported_dll_function kbdhookproc (INT ncode, wparam, lparam)
{
Bool bhandledkeystroke = false;
If (DWORD) lparam & 0x40000000) & (hc_action = ncode ))
{
Switch (wparam)
{
Case vk_f1:
Afxmessagebox ("the F1 button is captured! ");
Bhandlekeystroke = true;
Break;
Default:
Break;
}
}
Return (bhandledkeystroke? True: callnexthookex (ghkeyhook, ncode, wparam, lparam ));
}
One of the values that ncode may contain is the hc_action constant. In fact, this parameter can only be one of two values: hc_action and hc_noremove. In both cases, the wparam and lparam variables will contain information about the keys. If the ncode is less than 0, the filter function should not process the strike key, but call the callnexthookex function.
Next, export the DLL function. First open the keybdhook. h file and declare a function for installing or setting the keyboard HOOK:
Bool _ stdcall installkeyboardhook (hwnd );
The implementation is as follows:
Bool exported_dll_function installkeyboardhook (hwnd)
{
Bool bsuccess = false;
If (! Ghkeyhook)
{
Ghwndmain
= Hwnd;
Glpfnhookproc
= (Hookproc) kbdhookproc;
Bsuccess = (null! = (Ghkeyhook =: setwindowshookex (wh_keyboard, glpfnhookproc, ghinstance, null )));
}
Return bsuccess;
}
You also need to export a function to release the HOOK:
Bool exported_dll_function deinstallkeyboardhook ()
{
If (ghkeyhook)
{
If (true = (0! =: Unhookwindowshookex (ghkeyhook )))
{
Ghkeyhook = NULL;
}
}
Return (null = ghkeyhook );
}
If you look at the DLL generated by MFC Code It is easy to see that the DLL class is derived from the cwinapp class and implements the initinstance member function. The initial trial Code required by the DLL should be provided here.
The advantage of using the cwinapp class is that you can perform DLL programming like any other cwinapp derived class. For example, you can reload the DLL cwinapp: initinstance function and provide global initialization. Although MFC provides
The default dllmain implementation, but we recommend that you initialize it in the initinstance function of the cwinapp derived class of the DLL. This is required in many cases.
Bool ckeybdhookapp: initinstance ()
{
Afx_manage_state (afxgetstaticmodulestate ());
Ghinstance = AfxGetInstanceHandle ();
Return true;
}
Int ckeybdhookapp: exitinstance ()
{
Deinstallkeyboardhook ();
Return cwinapp: exitinstance ();
}
In this way, all the hook functions for capturing keyboard keys are created. The use of DLL is convenient for customers (applications or other DLL) to export and call. To test the keyboard Hook, you can create a dialog box based on
Keybdhookclient. Assume that you create a message handler for the click OK button event and call the installkeyboardhook export function of DLL in the handler:
Void ckeybdhookclientdlg: onok ()
{
Installkeyboardhook (getsafehwnd ());
}
Overload dialog box oncancel Function
Void ckeybdhookclientdlg: oncancel ()
{
Deinstallkeyboardhook ();
Cdialog: oncancel ();
}
Do not forget to add # include "keybdhook. H" before the keybdclientdlg. cpp File"
To test this hook program, you can find a program that uses F1. When you start your keybdhookclient application and press "f1" in other software programs, a message box will pop up, and the system will tell you to capture the key message.
OK! Today's lecture is over!

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.