Hook monitoring principles and application technology for Windows Keyboard Events

Source: Internet
Author: User


In order to monitor various event messages in the system in applications, indow's Message Processing Mechanism provides various callback functions. This hook function is similar to extending the interrupt driver. Multiple reverse functions can be attached to the hook to form a function chain. Messages generated by the system are first sent to various hook functions, which monitor, modify, and control messages based on their respective functions, then return control or pass the message to the next hook function so that the window function is reached. Although this method of calling inverse functions in the window system will slightly affect the operating efficiency of the system, it is very useful in many cases, you can use the hook function monitoring mechanism of keyboard events reasonably and effectively to achieve unexpected results.



I. How to mount monitoring functions on Windows Keyboard Events



There are 11 types of filtering functions that can be mounted in window:
H_callwndproc Window Function Filter Function
H_cbt computer training filtering function
H_debug debug filter functions
H_getmessage: message filtering function
H_hardware hardware message filtering function
H_journalplayback message replay filtering function
H_journalrecord message record filtering function
H_mouse mouse Filter Function
H_msgfilter message filtering function
H_sysmsgfilter system message Filter Function
H_keyboard keyboard Filter Function



The keyboard filter function is the most commonly used and useful filter function type. No matter which type of filter function is used, the basic method of attaching the function is the same. Window always calls the function at the beginning of the chain when calling the reverse call function. Therefore, you must use the setwindowshookex () function to hook the function at the beginning of the function chain. Whether a message is transmitted to the next function of the function chain is determined by each specific function. If the message needs to be traditionally sent to the next function, you can call callnexthookex () of the API function to implement it, if this parameter is not passed, return directly. The hook function can be a global function used to monitor messages of all threads, or a local function that separately monitors a thread. If the hook function is a local function, you can place it in one. DLL dynamic link library can also be placed in a local module; if the hook function is global, it must be placed in one. DLL dynamic link library. The hook function must be declared in the following format:
NT far Pascal keyboardproc (
NT ncode, word wparam, DWORD lparam)
Keyboardproc in defines the hook function name, which must be described using the exports command in the module definition file; ncode determines whether the hook function processes the current message; wparam and lparam are specific message content.



Ii. Install and download the keyboard event Hook Function



The setwindowshookex () function can be used in the program to mount the filter function. When mounting the function, you must specify the type of the function, the function entry address, and whether the function is global or local, the Calling format of the hook function is as follows:
Etwindowshookex (itype, iproc, hinst, icode)
Here, itype is the hook function type, the keyboard type is wh_keyboard, iproc is the hook function address, hinst is the hook function Linked Library instance handle, and icode is the monitoring code-0 indicates the global function. If the hook function needs to pass messages to the next filter function, call the callnexthookex () function before the hook function returns. When you need to download the hook function, you only need to call the unhookwindowshookex (iproc) function once. If the function is global, it must be placed in a. dll dynamic link library. At this time, the function call method can be the same as other common. DLL functions:



1. Use the function name or serial number in the def definition file:
Exports
WEP @ 1 residentname
Inithooksdll @ 2
Installfilter @ 3
Keyboardproc @ 4
The serial number format is: name of the Linked database. function name (in this example, the method is keydll. keyboardproc ).



2. directly call functions in an application:
First, use loadlibrary (lpstr "") in the application to load the Dynamic Linked Library, obtain the handle hinst of the loaded library module, and then directly use getprocaddress (hinstance hinst, lpstr "function process name") to obtain the function address, and then directly call this address. Before the program ends, use the function freelibrary () to release the loaded dynamic link library.



3. Use the input library. Lib Method
Use the implib. exe program to create the corresponding Input library. Lib while creating the dynamic link library, and then directly add the input Library to the project file.



Iii. Implementation steps of Windows Hook monitoring functions



The Windows hook function can monitor all events only when it is placed in the dynamic link library DLL. The basic method and structure of hook monitoring functions in. dll are as follows:
1. First declare the variables and procedures in the DLL;
2. Compile the main DLL module libmain () and create a module instance;
3. Establish the WEP () function of the system exit DLL mechanism;
4. Complete the DLL initialization function inithooksdll () and pass the main window program handle;
5. Compile the hook installation and download function installfilter ();
6. Compile the hook function keyboardproc (), set the monitoring function, and determine whether to continue to call the hook function or directly return to the Windows application.
7. initialize the DLL in the Windows main program and install the corresponding hook function. The hook function is responsible for communicating with the main program;
8. When no monitoring is required, the download function disconnects the hook function.



Iv. Application Technology of keyboard hook monitoring functions in Windows



There are two special buttons on the standard 104 keyboard. They are marked by the window Program Logo and the mouse drop-down list respectively, the former is used to simulate the left mouse button to activate the Start menu, and the latter is used to simulate the right mouse to activate the attribute menu. These two special buttons can be used only when they are immediately lifted after being pressed to complete the click process. They are not used in combination with other buttons. In Windows, buttons are divided into more details, making it difficult for applications to flexibly define their own dedicated shortcut keys, such as in development. for applications such as IME, it is difficult to find function buttons that do not conflict with other applications such as word8.0. If the two special buttons in the standard 104 keyboard are used as the simulated CTRL and ALT buttons and combined with other keys, you can freely set the dedicated function keys in your own applications, provides flexibility for applications to implement various functional shortcut keys. Under normal circumstances, the Windows keyboard event driver does not properly interpret the messages of the two buttons. Therefore, you must use the keyboard event hook monitoring function to implement its specific functions. The method is as follows:



1. Compile a simple dynamic link library program and compile it into a DLL file.
 # Include "windows. H "<br/> int far Pascal libmain (handle hmodule, uint wdataseg, <br/> uint cbheapsize, lpstr lpszcmdline); <br/> int winapi WEP (INT bsystemexit ); <br/> int winapi inithooksdll (hwnd hwndmainwindow); <br/> int winapi installfilter (bool ncode); <br/> lresult callback keyhook (INT ncode, word wparam, DWORD lparam); <br/> static handle hinstance; // Global handle <br/> static hwnd hwndmain; // Main Window handle <Br/> static int initcalled = 0; // initialization flag <br/> static hhook hkeyhook; <br/> farproc lpfnkeyhook = (farproc) keyhook; <br/> bool hookstates = false; <br/> int far Pascal libmain (<br/> handle hmodule, <br/> uint wdataseg, <br/> uint cbheapsize, <br/> lpstr lpszcmdline) <br/>{< br/> If (cbheapsize! = 0) unlockdata (0); <br/> hinstance = hmodule; <br/> return 1; <br/>}< br/> int winapi WEP (INT bsystemexit) <br/> {return 1 ;}< br/> int winapi inithooksdll (hwnd hwndmainwindow) <br/> {hwndmain = hwndmainwindow; <br/> initcalled = 1; <br/> return (0); <br/>}< br/> int winapi installfilter (bool ncode) <br/> {If (initcalled = 0) return (-1); <br/> If (ncode = true) {<br/> hkeyhook = setwindowshookex (wh_keyboard, <br/> (hookproc) lpfnkeyhook, hinstance, 0); <br/> hookstates = true; <br/>}else {<br/> unhookwindowshookex (hkeyhook); <br/> hookstates = false; <br/>}< br/> return (0); <br/>}< br/> lresult callback keyhook (INT ncode, word wparam, DWORD lparam) <br/>{< br/> static bool msflag = false; <br/> If (ncode> = 0) {<br/> If (hookstates = true) {<br/> If (wparam = 0xff) | // key value in win3.x <br/> (wparam = 0x5b) | (wparam = 0x5c )) {// key value in Win95 <br/> If (I = 0x15b) | (I = 0x15c )) {// press <br/> msflag = true; <br/> postmessage (hwndmain, 0x7fff, 0x1, 0x3l ); <br/>} else if (I = 0xc15b) | (I = 0xc15c) {// press the button to lift the handle <br/> msflag = false; <br/> postmessage (hwndmain, 0x7fff, 0x2, 0x3l ); <br/>}< br/> return (INT) callnexthookex (hkeyhook, ncode, wparam, lparam); <br/>}</P> <p>

The main function of the program is to monitor the keyboard key messages, convert the two special keys micro press and lift the messages into custom types of messages, and send custom messages to the application Main Window Function.



2. After creating a window in the main function of the application, call the inithooksdll () function to initialize the dynamic link library, pass the main window handle of the application to the link library, and then call installfilter () function hook keyboard event monitoring callback function.
Inithooksdll (himewnd); // initialize the DLL
Installfilter (true); // install the keyboard callback function



3. When the Main Window Function of the application processes a custom message, the status of the micro button is saved for judgment and use when the combination of buttons is processed.


4. When performing button combination processing, first determine whether the micro key is pressed, and then judge and process other buttons.
Case wm_keydown: // press the button <br/> If (microflag = true) {// press the micro key <br/> If (byte) hibyte (wparam) = 0x5b) {<br/> // micro + "[" combination key <br/> ...... <br/> // button processing <br/>} else if (byte) hibyte (wparam) = 0x5d) {<br/> // micro + "]" key combination <br/> ...... <br/> // button processing <br/>}< br/> break; <br/>


5. When the application exits, pay attention to downloading the keyboard monitoring function, that is, calling the installfilter (false) function once.



6. Use the methods provided in this article to set your own application function buttons. while ensuring that the program function buttons do not conflict with other systems, you can effectively use existing resources in the system, in addition, while implementing application functions, various functions provided by the system are flexibly applied.

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.