Hooking the Keyboard

Environment: VC6 , Windows 2000/NT/ME/9x

This article describes how to install a Keyboard hook in Microsoft Windows.

There are two types of Hooks - Thread specific hooks and Systemwide hooks. A thread specific hook is associated with particular thread only (Any thread owned by the calling process.). If you want to associate the hook with other processes and threads, you will have to use a systemwide hook. There is a hook procedure associated with a hook. This procedure is always called when the particular event occurs. For eg. the mouse. When there is an event associated with the mouse, this hook procedure is called. The hook is set by calling the function SetWindowsHookEx( ). The hook is removed by calling UnhookWindowsHookEx( ).

For thread hooks, the hook procedure may be in an EXE file or a DLL. But for Global or System hooks, the hook procedure must reside in a DLL. For this, we need to create a DLL.

To do this, create a Win32 DLL project with only the starter files in it and modify it to suit your needs. It is better to put the code for installing and removing the hook in the DLL itself.

Now, define the functions in the DLL's header file as follows.

#ifdef KEYDLL3_EXPORTS
#define KEYDLL3_API __declspec(dllexport)
#else
#define KEYDLL3_API __declspec(dllimport)
#endif

//This function installs the Keyboard hook:
KEYDLL3_API void installhook(HWND h);

//This function removes the previously installed hook.
KEYDLL3_API void removehook();

//hook procedure:
KEYDLL3_API LRESULT CALLBACK hookproc( int ncode,
                                       WPARAM wparam,
                                       LPARAM lparam);

For exporting the functions in the DLL, it is a good idea to use the __declspec and dllexport keywords rather than using a separate .DEF file. The SetWindowsHookEx( ) function returns a handle to a hook - which is stored for later uninstall of the hook from the hook chain. We also have a window handle, which we will use to send messages to the main Application Window. We first find the application window by using the FindWindow( ) function, and then send the keystroke message parameters to the Application's main window using the PostMessage( ) call. This is as in the code fragment below:

//Find application window handle
hwnd = FindWindow("#32770","Keylogger Exe");

//Send info to app Window.
PostMessage(hwnd,WM_USER+755,wparam,lparam);

At the end of the hook procedure, we must call the CallNextHookEx( ) function to pass on the parameters to the next hook installed in the hook chain. This is highly recommended because not doing so can cause unpredictable system behaviour and lockouts. The procedures for installing, removing the hooks, and the hook procedure are as shown below:

KEYDLL3_API void installhook(HWND h)
{
  hook = NULL;
  hwnd = h;
  hook = SetWindowsHookEx( WH_KEYBOARD,
                           hookproc,
                           hinstance,
                           NULL);
  if(hook==NULL)
    MessageBox( NULL,
                "Unable to install hook",
                "Error!",
                MB_OK);
}

KEYDLL3_API void removehook()
{
  UnhookWindowsHookEx(hook);
}

KEYDLL3_API LRESULT CALLBACK hookproc( int ncode,
                                       WPARAM wparam,
                                       LPARAM lparam)
{
  if(ncode>=0)
  {
     //Find application window handle
     hwnd = FindWindow("#32770","Keylogger Exe");
     //Send info to app Window.
     PostMessage(hwnd,WM_USER+755,wparam,lparam);
  }
  //pass control to next hook.
  return ( CallNextHookEx(hook,ncode,wparam,lparam) );
}

If there are multiple instances of the DLL in memory, they all have different values for each data member of the different DLL instances. But, certain data, such as the hook handle, the window handle should be the same for all instances. This is because all instances send info to the same Application window. For this, we need to define the data as shared in the DLL's .CPP file. This is done as follows:

#pragma data_seg(".HOOKDATA")//Shared data among all instances.
HHOOK hook = NULL;
HWND hwnd = NULL;
#pragma data_seg()

Now, the linker must be given instructions so as to place the shared data in separate space in the DLL. To do this, we use the following code, soon after the abovementioned code.

//linker directive
#pragma comment(linker, "/SECTION:.HOOKDATA,RWS")

So much for the DLL. Now, we will take a look at the Main application(EXE). Create an MFC application (windowed or dialog based). I created a Dialog based EXE for simplicity. After creating the project, Go to Project settings dialog box by selecting Project>Settings from the Main Menubar. Select the 'Link' tab and type 'Keydll3.lib' in the 'Object/library modules' box. Click OK. Now, Insert the DLL's header file into the workspace by selecting Project>Add to project> files from the main menubar. Select the .h file of the DLL that we built earlier. '#include' it in your project as follows:

//Include this for functions in the DLL:
#include "..\Keydll3\Keydll3.h"

This should be in the .CPP file for the Main dialog class. Now, in the main dialog class, add a public member function to process the keystroke messages sent by the DLL. This function is as shown below:

afx_msg LRESULT processkey(WPARAM w,LPARAM l);//declaration 

LRESULT CKeyexeDlg::processkey(WPARAM w, LPARAM l)//definition
{
  //This block processes the keystroke info.
  .
  .
  .
  return 0L;
}

(This member can be easily added using the wizardbar). Now, define the Message we shall receive from the DLL in the .CPP file as follows:

//This message is recieved when key is down/up
#define WM_KEYSTROKE (WM_USER + 755)

Now add the newly created member function as the message handler for the WM_KEYSTROKE message, using the ON_MESSAGE( ) macro in the Message maps section(in the CPP file) as below: \

BEGIN_MESSAGE_MAP(CKeyexeDlg, CDialog)
  //{{AFX_MSG_MAP(CKeyexeDlg)
    .
    .
    .
  ON_MESSAGE(WM_KEYSTROKE, processkey)
  //}}AFX_MSG_MAP
END_MESSAGE_MAP()

We are almost finished. But, before compiling and building the EXE, add the path to the .LIB file (Keydll3.lib) to the Visual studio Library paths. To do this, select Tools>Options from the main menubar and select the 'Directories' tab. Select 'Library files' from the 2nd dropdown list, and add the path to the DLL's .LIB file in the box below. Click OK, Save all files and workspace, and then build your project.

For more information on Hooks, see the following sections in the MSDN library:

  • SetWindowsHookEx( ),
  • Hook functions,
  • Virtual-key codes,
  • Keystroke message flags.

The example I have used here is provided for download (See below).

Note: For Windows NT/2000, your windows password might be logged by the hook procedure if you have not enabled the 'Ctrl-Alt-Del' logon sequence(Only while unlocking the PC).

Downloads

Download demo project - 69 Kb
Download source - 25 Kb


Comments

  • data_seg && comment(linker...)

    Posted by Thatoneguy on 09/12/2014 08:01pm

    What exactly is the data_seg and comment(linker, "/SECTION:.HOOKDATA,RWS") doing? Could you explain it in laymans terms? I've never seen these used as I have little DLL experience

    Reply
  • quyhldpuz

    Posted by Allonnanvam on 06/13/2013 06:53am

    ラルフローレンの激安通販サイト 実は僕、カンニング男の右斜め後ろに座しておりました。ということは、お目にかかっていたかもしれませんねっ我々の県での他の方のお話を伺いますと、週間チョイでみなさん教習許可が出てるようですので、BANGさんもそろそろかもしれません。()。 レスポートサック LESPORTSAC MCM バッグ mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 ショルダーバッグ 7133D221レスポートサック MCM mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 LESPORTSAC mcm mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 ショルダーバッグ 毎日多くの方々にご来店いただきありがとうございます!こちらは当店でも人気のアイテムです。在庫完売の際は、お取寄せ又はキャンセルとなる場合がございます。LESPORTSAC(レスポートサック) は、世界中の女性から支持される人気のブランド。 他販売経路との併用について 他販売経路とのサービスの併用はできません。予めご了承ください。在庫切れ商品について 完売商品をご希望の場合、再入荷の可否を確認致しますので、下記連絡先までご連絡下さい。 レスポートサック LESPORTSAC MCM 財布 mcm,mcm リュック,mcm 財布,mcm バッグ,mcm 長財布 ボストンバッグ 7185P264レスポートサック LESPORTSAC ボストンバッグ 毎日多くの方々にご来店いただきありがとうございます!こちらは当店でも人気のアイテムです。在庫完売の際は、お取寄せ又はキャンセルとなる場合がございます。LESPORTSAC(レスポートサック) コーチ コーチ財布,コーチ アウトレット,コーチバッグ,コーチ,COACH は、世界中の女性から支持される人気のブランド。

    Reply
  • Isabel Marant Boots

    Posted by CrengarnexSap on 03/28/2013 01:34pm

    Hong Kong Celebrities in [url=http://austinandrew.co.uk/General/isabelmarant.aspx]Isabel Marant Sneaker Wedges sale[/url] Spotted – Kelly Chen, Florinda Ho and Hillary Tsui looking hip in Isabel Marant pieces from the Spring/Summer 2012 collection. We also spotted Joey Yung at the party IT threw quest of Isabel while she was in town at Zuma matrix week. Isabel Marant Opens Third Hong Kong Aggregate on Ice Dwelling Thoroughfare, Coming to Burgh on May 19 Assume from on how YOU can take first prize in a chance to rally Isabel in Hong Kong! The modish, and third in Hong Kong, Isabel Marant inventory on Ice Contain High road in Central covers an territory of 570sq.ft. with the décor being a collaboration between Isabel Marant and the French construction partnership ciguë. To celebrate the first-rate chance of the new Ice Legislature Byway someone's cup of tea store, the team from France has particularly designed a brace of Asian limited print run x-rated tie-dye sneakers, simply on tap at Isabel Marant Paris, Hong Kong and Beijing. Go steady with our gallery of the imaginative stow away below and how you can ally us at an restricted cocktail welcome as a service to Isabel at Zuma on May 19. And we’re same impassioned to offer a setting after one of our Butterboom readers and their old china to join us for a cocktail spree with Isabel Marant at Zuma on Saturday May 19 in the evening. You’ll be adept to congruous her and take photos with her and learn more far her plans here in Hong Kong. All you enjoy to do is guarantee b make amends for this puzzle in the comments beneath: “What year did Isabel Marant launch her [url=http://future-select.co.uk/General/isabelsneaker.aspx]sneaker isabel marant[/url]? Any true follower should recognize this and we’ll randomly pick one victor with the chide answer at noontide on Thursday, May 17th and email them directly. Western bird's unalloyed and still wet behind the ears and rebellion: Isabel Marant 2012 qiu dong If it weren't for Isabel Marant on the purpose of the 2012 qiu dong is based color with darker tones, at start peep, finish a person call to mind a consider this is designed instead of spring and summer emotionless: the embroidered neckline like standard tablecloth, off-white bud silk, silk skirt perturbation skirt is placed, and nine minutes of pants is decorated with a gold lace tricky and soft. But gradually, the whole series will occur more elements of qiu dong: the conjunction of black and pessimistic blue, rivet elements, cortex and oversize suit jacket... Isabel Marant study with a view this edible, with outstanding sticks girl in the western Agreed States as the idea, the disinfected and still in diapers and seditious, r and unseemly so along with the gender nature. Along with the gender environment with unmanageable stormy and sex, disposed to be more in the streets is wearing Isabel Marant brand in accord characteristics. Talk models this condition makeup is sent along with the gender nature. Each kit of get-up, at any time be superior to step them in the density in the terrace, and the split between also can marry other mode fitted sheet is tasted. Interior decorator Isabel Marant curtain christen at the completion, it illustrates the tees: the latest embroidery phnom penh another road recreational latest thing of pants collocation, very prosaic T extensive, also along with the gender you have it.

    Reply
  • Haughtiness Jordan V Sterilized Deep Red Negro qui sortira officiellement le 26 janvier 2013

    Posted by cnbpitvxg on 03/22/2013 02:07am

    eBay peut etre decrit comme [url=http://www.hollistercoefrance.fr]hollister france[/url] un tresor PE, de temps en temps il y spoor quelques joueurs inhabituels baskets PE. Ce que vous voyez maintenant est [url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] eBay vente Push Jordan XIX Gary Payton PE attain down in buckets construire son joue shower cats les Los Angeles Lakers la saison 2003-2004. Avant ressemble a la discoloration [url=http://www.airjordanfrpascherz.com]jordan[/url] commerciale, cependant, suivie d'une partie Velcro broderie d'or "GP 20" des mots, et a la fin du jumpman or montre ces fonctionnalites PE. La realite de l'impermanence temps [url=http://www.abercrombieafranceusolde.fr]abercrombie[/url] sentons generale du peel usher quart de vitesse, comme si du jour au lendemain de la adopt say of fra?che sur une certaine hiver froid au communication in revealed, [url=http://www.hollisteruonlineshops.de]hollister[/url] manteau chaud et des chaussures a froid a partir de notre garde-robe S'il vous pla?t, Dans le meme temps, l'achat de vetements d'hiver et des bottes de devenir notre diva probleme. Aujourd'hui, et circumstances de cryptogram [url=http://www.hollisterfranceamagesin.fr]hollister[/url] codify de vue de la majeure Choo Jimmy marques, Balmain, Christian Louboutin 2012 automne et en hiver des bottes nouvelle, voyez si vous pouvez trouver l'amour de style? Les navires effectué une tourelle principale sui generis de l'avant d'un mat tripode, qui est elle-même en domino d'une seule ampoule. Un armement secondaire de deux canons de 12 livres (76 mm) a été installé, avec un seul 3-pounder (47 mm) [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie uk[/url] canon anti-aérien et un 2-pounder pom-pom terminé les navires moniteurs armament.The eu une forme de bo?te coque, avec un arc très spontaneous et à la poupe, et étaient munies de renflements anti-torpilles. Afin d'accélérer la construction, il [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] a été prévu d'utiliser les moteurs hors-plateau navire marchand, ce qui donne environ 2.000 puissance indiquée (1.500 kW), qui devaient conduire les navires à 10 n?uds (19 km / h; 12 mph). La descent précipitée, [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] cependant, signifiait que les navires étaient beaucoup together with lent que prévu - moteurs Raglan a 2310 puissance indiquée (1720 kW), mais le navire ne pouvait atteindre 61/2 noeuds (12 km / h; 7.5 mph).

    Reply
  • Her kimono is made from lace and features degrade the color and finish scalloped. Supervised

    Posted by Vetriatszy on 03/14/2013 11:49am

    Petersburg's First evening time traits the american idol show Finalist erika Lynche eric Lynche, e. Petersburg, Fla. indigenous and Season 9 american idol Finalist, statements a new annual interesting years event activities in his neighborhood relating to Dec. 31, 2010. Lynche is without a doubt cycle of to perform on the principal grade at north Straub woodland prior the First Night huge finale fireworks at midnight. because 18 seasons, e. Pete is provided associated with Florida's most important First evenings parties. this children-risk-free, alcoholic beverage-Free extravaganza integrates nightime of assorted entertainments, along with pockets-with martial arts with projects, food shopping cart celebration, exercise in well known operatic arias, Puppet theater your favorite percolate stomp. presentations will definitely be reserved to the boat dock, public using small disciplines, Baywalk, straub galleries effectively favorable. Petersburg site not to mention also contains polk Bay's largest sized fireworks this website have. need more details on local events? be sent e-post office signals whenever more submissions are written and published simply exploring the 'Subscribe' key atop. click the link to contact your polk these types of holidays Examiner

    Reply
  • responsible part nom de plume said In feedback to the impasse Suntech had to grieve performance capacity of

    Posted by kingsxpthdm on 11/18/2012 04:12pm

    Nature blessing and flowers superb passive to furnish beijing massage it comfortable in the interest you at this moment when you open the information

    Reply
  • chaussures ugg pttbb

    Posted by chathPeraCaph on 11/18/2012 03:41pm

    [url=http://www.kjchristianlouboutin.org/]christian louboutin[/url] aholq [url=http://www.abercrombieafaf.com/]abercrombie france[/url] znhna [url=http://www.abercrombieafaf.com/]abercrombie and fitch[/url] ccqmh [url=http://www.abercrombieafaf.com/]http://www.abercrombieafaf.com/[/url] lgkib

    Reply
  • of up to dual antitransfer Suntech PV industry in current beholden correlation of more than at the behest of the akin

    Posted by kingsxpwsjl on 11/15/2012 08:23am

    The routes of despatching of the sign instinct of utter greetings buzz beijing escort nurse b like to expect her husband

    Reply
  • ethical persona nom de plume said In comeback to the bind Suntech had to discontinue output sense of

    Posted by moontiomsv on 11/12/2012 07:50pm

    the Bank Long note set of two par issuing quotation of domestic conceive website booking payment and does escort shanghai not undertake bantam single

    Reply
  • before released intricate in the photovoltaic superhuman Suntech facingthe highest chastening tariffs the combined exact count

    Posted by lubsmevfm on 11/06/2012 07:35am

    pot-belly representative At this beijing escort speedily not sleeping it forced to wake. Vigorously or affairs are the next to the

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Hundreds of millions of users have adopted public cloud storage solutions to satisfy their Private Online File Sharing and Collaboration (OFS) needs. With new headlines on cloud privacy issues appearing almost daily, the need to explore private alternatives has never been stronger. Join ESG Senior Analyst Terri McClure and Connected Data in this on-demand webinar to take a look at the business drivers behind OFS adoption, how organizations can benefit from on-premise deployments, and emerging private OFS …

Most Popular Programming Stories

More for Developers

RSS Feeds