Windows applications that use hook functions to capture keyboard responses

Source: Internet
Author: User
From: http://edu.qudong.com/program/C/shilijiexi/20080512/11946.html 1: Introduction: You may have been confused about Kingsoft's screen grasp word implementation principle, you may want to record your keyboard, mouse activity at the right time, you even want to know how a trojan loads a trojan dll in the Windows operating system ..... In fact, these are all Windows hook functions. Therefore, this article will elaborate on the knowledge of hook functions. Of course, the purpose of this article is not to allow readers to steal others' passwords through this program, but because the hook function is a very important system interface function in Windows systems, so I want to discuss it with you. Of course, this article also gives a simple description of how to establish a dynamic link library (DLL. (The program in this article is the development environment of vc6.0. The languages are C and Win32.
API ). Ii. Hook Overview: Microsoft's windowsx operating system is based on an event-driven mechanism, that is, implemented through message transmission. In Windows, hooks are a mechanism for receiving events before an event (such as message, mouse activation, and keyboard response) arrives at an application. In addition, the hook function can also be used to modify or discard events.
Windows has two types of hooks: thread specific hooks and systemwide hooks ). A specific thread hook only monitors a specified thread, while a global system hook can monitor all threads in the system. Both a specific thread hook and a global system hook are set through setwindowshookex. For special thread hooks, the hooks can be either included in A. EXE or a. dll. However, for a global system hook, the hook function must be included in an independent DLL. Therefore, when we want to capture the keyboard response, we must create a dynamic link library. However, when the hook function is under control and the relevant event is processed, if you want to continue the message transfer, you must call another function: callnexthookex. Because the system must process each message, the hook Program increases the processing burden and reduces the system performance. In view of this, in Windows
The hook subroutine in CE is not supported. Therefore, when the program is completed and exited, you should release the hook and call the function: unhookwindowshookex.
The following is an example (capturing the keyboard) to explain in detail the program design of the hook function. Iii. Program Design: I: set the hook to use the setwindowshookex () API function.
Prototype: hhook setwindowshookex (INT idhook, hookproc lpfn, hinstance hmod, DWORD dwthreadid)
Idhook: the type of the hook to be loaded.
Lpfn: Entry address of the hook Process
Hmod: Application Event handle
Dwthreadid: Specifies the thread parameter for mounting the HOOK:
Idhook:
This parameter can be of the following values:
Examples, examples, wh_cbt, wh_debug, examples, wh_getmessage, wh_journalplayback, wh_journalrecord, wh_keyboard, examples, wh_mouse, wh_mouse_ll, wh_msgfilter, wh_shell, and wh_sysmsgfilter.
I don't want to explain these parameters one by one, because msdn has their detailed annotations. I only select a few of them for Chinese instructions.
Wh_keyboard: once there is a keyboard hitting message (press the keyboard and the keyboard pops up), Windows will call your hook function before the message is placed in the message queue of the application. The hook function can change or discard the keyboard hitting message.
Wh_mouse: each mouse message is placed in the application's message queue before Windows will call your hook function. The hook function can change or discard mouse messages. Wh_getmessage: every time your application calls a getmessage () or peekmessage () to request a message from the application's message queue, Windows will call your hook function. The hook function can change or discard the message. II: The unhookwindowshookex () function is used to release hook.
Prototype: bool unhookwindowshookex (hhook HHK)
The unhookwindowshookex () function releases the hook process loaded by the setwindowshookex function in the hook chain.
HHK: handle of the hook process to be released. III: hook process uses the hookproc function. In fact, hookproc is only a symbol defined by the application. For example, you can write keyboardhook, but the parameters remain unchanged. Win32 API provides functions such as CALLWNDPROC, getmsgproc, debugproc, cbtproc, mouseproc, keyboardproc, and messageproc. For details, refer to msdn. Here I will only explain the meaning of keyboardhook.
Prototype: lresult callback keyboardhook (INT ncode, wparam, lparam)
Note: The Hook process is a number of functions attached to a hook. Therefore, the hook process is called only by windows and not by applications, they sometimes need to be called back ). Parameter description:
Ncode: hook code. The hook process uses the hook code to determine whether to execute the code. The value of the hook Code depends on the type of the hook. Each hook type has its own series of code features. For example, for wh_keyboard, the hook code parameters include hc_action and hc_noremove. Hc_action meaning: The wparam and lparam parameters contain information about the keyboard hitting message. hc_noremove meaning: The wparam and lparam parameters contain information about the keyboard hitting message, and, the keyboard hitting message has not been deleted from the message queue. (The application calls the peekmessage function and sets the pm_noremove flag ). That is to say, when ncode is equal to hc_action, the hook process must process the message. For hc_noremove, the hook process must pass messages to the callnexthookex function, rather than further processing, and must have the return value of the callnexthookex function.

Wparam: the keyboard message generated by a keyboard knock and the virtual code of the keyboard buttons.
Lparam: contains the Message Details. Note: If the ncode In the hook process is less than zero, the hook process must return (return) callnexthookex (ncode, wparam, lparam); while the ncode In the hook process is greater than zero, however, the hook process does not process messages. We recommend that you call callnexthookex and return the return value of this function. Otherwise, if the wh_keyboard hook is mounted to another application, the hook will not receive the hook notification and return an incorrect value. If the hook process processes messages, it may return a non-zero value to prevent the system from passing the information to other hooks or Windows processes. Therefore, it is best to return the callnexthookex return value at the end of the hook process.
IV: callnexhookex is used when the next hook function is called.
Prototype: The lresult callnexthookex (hhook HHK, int ncode, wparam, lparam) callnexhookex () function is used to transmit hook information to the next hook process in the current hook chain, A hook process can call this function either before the hook information is processed or after the hook information is processed. The usage of this function has been described in detail in "NOTE" in the III hook process.
HHK: handle of the current hook
Ncode: the hook code sent to the hook process.
Wparam: The value sent to the hook process.
Lparam: The value sent to the hook process.
Parameters:
HHK: the handle of the current hook. The application accepts this handle as the result of the previous call to the setwindowshoke function.
Ncode: the hook code sent to the hook process. The next hook process uses this code to determine how to handle the hook information.
Wparam: The wparam parameter value sent to the hook process. The specific meaning of the parameter value is related to the hook type of the current hook chain.
Lparam: The wparam parameter value sent to the hook process. The specific meaning of the parameter value is related to the hook type of the current hook chain.
Return Value: The returned value is the value returned by the next hook process in the chain. The current hook process must return this value. The specific meaning of the returned value is related to the hook type of the hook, for more information, see descriptions of hook processes.

V. Create a dynamic connection library (DLL). When we are familiar with the above functions, we are now writing a dynamic connection library (DLL ). Here I use Win32 DLL instead of MFC DLL. All of the following programs are also written in C language. This is mainly because the Win32 API can be used to control how programs are executed in a more detailed and comprehensive manner. However, when using MFC, some low-level controls are impossible (of course, only for this program, you can also use MFC ). 1: Create a. cpp file for the dynamic Connection Library. For example, we create a file named hookdll. cpp. Add the following content to the hookdll. cpp file:
#include <windows.h>#include "string.h"#include "stdio.h" HINSTANCE hInst;#pragma data_seg("hookdata")HHOOK oldkeyhook=0;#pragma data_seg()#pragma comment(linker,"/SECTION:hookdata,RWS")#define DllExport extern "C"__declspec(dllexport)DllExport LRESULT CALLBACK KeyBoardProc(int nCode,WPARAM wParam, LPARAM lParam );DllExport void InstallHook(int nCode);DllExport void EndHook(void);BOOL WINAPI DllMain(HINSTANCE hInstance,ULONG What,LPVOID NotUsed){switch(What){case DLL_PROCESS_ATTACH:hInst = hInstance;break;case DLL_PROCESS_DETACH:break;case DLL_THREAD_ATTACH:break;case DLL_THREAD_DETACH:break; }return 1;}void InstallHook(int nCode){oldkeyhook = SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyBoardProc,hInst,0);}DllExport LRESULT CALLBACK KeyBoardProc(int nCode,WPARAM wParam, LPARAM lParam ){WPARAM j;FILE *fp;if(lParam&0x80000000){j = wParam;fp=fopen("c:\\hook\\key.txt","a"); fprintf(fp,"%4d",j);fclose(fp);}return CallNextHookEx(oldkeyhook,nCode,wParam,lParam);}void EndHook(void){UnhookWindowsHookEx(oldkeyhook);}
The source code hookdll. cpp of the dynamic Connection Library contains the keyboard processing function, which sets the hook and exits the hook function. Then, save the key that you typed on the keyboard as a value to the C: \ hook \ key.txt file. The following is a detailed explanation of the file.
To use a function included in a DLL, you must import it. Dllimport is used to complete the import. Both dllexport and dllimport are extensions supported by VC (Visual C ++) and BC (Borland C ++. However, the dllexport and dllimport keywords cannot be used by themselves. Therefore, it must have another extension keyword _ declspec. The common format is __declspec (specifier). specifier is the storage class identifier. For DLL, specifier will be dllexport and dllimport. To simplify the description of the statement for importing and exporting functions, replace _ declspec with a macro name. In this program, dllexport is used. If your DLL is compiled into a C ++ program and you want the C program to use it as well, add the "c" connection description. # Define
Dllexport extern "C" _ declspec (dllexport) to avoid corruption of Standard C ++ names. (Of course, if the reader is compiling a C program, do not add extern "C" because it is not needed and the compiler does not accept it ). With macro definition, you can now use a simple statement to export functions, such as dllexport lresult callback keyboardproc (INT ncode, wparam, lparam ); dllexport void installhook (INT ncode); dllexport
Void endhook (void );
The first # pragma statement creates a data segment, which is named hookdata. You can also name any name you like. # All initialized variables after The Pragma statement enter the hookdata segment. The second # pragma statement is the end mark of the Data Segment. Special initialization of variables is very important. Otherwise, the Compilation Program will put them in common uninitialized segments rather than in hookdata.
However, the linked program must still have a hookdata segment. We can select the link option in the project setting (vc6.0) dialog box, and select the hookdll in the project options field (both in the release and debug configuration), including the following connection statement:/section: hookdata, RWS letter RWS indicates that the segment has read, write, and share attributes. Of course, you can also directly use the DLL source code to specify the link program, just like hookdll. C: # pragma comment (linker, "/section: hookdata, RWS ").
Some DLL files require special startup and Termination codes. To this end, all dll has a function named dllmain (), which is called when the DLL is initialized or terminated. This function is generally defined in the resource file of the dynamic link library. However, if it is not defined, the compiler automatically provides the default format. Prototype: bool winapi dllmain (hinstance, ulong what, lpvoid notused)
Parameters:
Hinstance: DLL instance handle
What: Specifies the action
Notused: Reserved Parameter
The value of what can be:
Dll_process_attach: the process starts to use DLL
Dll_process_detach: the process is releasing the DLL.
Dll_thread_attach: the process has created a new thread.
Dll_thread_detach: the process has abandoned a thread.
In general, whenever the dllmain () function is called, appropriate actions must be taken based on what content. This appropriate action can do nothing, but does not return a non-zero value.
Dllmain () is followed by setting hooks, keyboard processing, and releasing hooks.

2: Create a header file
Just like any other library function used by the application, the program must also contain the prototype of the function in the DLL. All Windows programs must contain windows. h. So now we create a header file hookdll. h as follows:
# Define dllimport extern "C" _ declspec (dllimport)
Dllimport void installhook (INT ncode );
Dllimport lresult callback keyboardproc (INT ncode, wparam, lparam );
Dllimport void endhook (void );
Dllimport is mainly used to make the code more efficient, so it is recommended to use it. However, dllimport is required for data import. After the preceding program is completed, create a project named hookdll and. C is inserted into the project of the import project. After compilation, the hookdll can be generated. DLL and hookdll. lib. 3: Create the main program file
All the work we have done above is to lay the foundation for the current main program. In fact, after we complete the DLL file, the rest is to call the set hook function: installhook. If you are familiar with windows programming, you can call installhook whenever you need it. However, you must remember that when you exit the program, you need to call the endhook to release the hook function you have loaded. Now I have created a hookspy. cpp, copied the generated hookdll. dll and hookdll. lib to a directory, and created a hookspy project. Insert hookspy. cpp, hookdll. dll, hookdll. Lib, and hookdll. H to the project. Then, set the hook when creating the Windows window and exit the hook function when exiting the program. For example:
Case wm_create:
Installhook (true );
Break;
Case wm_destroy: // terminate the program
Endhook ();
Postquitmessage (0 );
Break;

 

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.