Click here to Skip to main content
Click here to Skip to main content

A Simple C# Global Low Level Keyboard Hook

By , 30 May 2007
 
Screenshot - key_preview.jpg

Introduction

This article discusses a class that I wrote that wraps a global low level keyboard hook. The sample hooks the A and B keys, just for demonstration.

Background

I was trying to find a way for an application that I am writing to restore itself when a combination of keys was pressed. This was born from searching around for the answer.

Using the Code

First download the source, and add globalKeyboardHook.cs to your project. Then add...

using Utilities;

... to the top of the file you are going to use it in. Next add an instance of globalKeyboardHook to your class:

globalKeyboardHook gkh = new globalKeyboardHook() ;

When a globalKeyboardHook is constructed, it automatically installs the hook, so all there is left to do is add some keys for it to watch, and define some event handlers for the KeyDown and KeyUp events. I usually do this on the main form's load event handler, like this:

private void Form1_Load(object sender, EventArgs e) {
    gkh.HookedKeys.Add(Keys.A);
    gkh.HookedKeys.Add(Keys.B);
    gkh.KeyDown += new KeyEventHandler(gkh_KeyDown);
    gkh.KeyUp += new KeyEventHandler(gkh_KeyUp);
} 

void gkh_KeyUp(object sender, KeyEventArgs e) {
    lstLog.Items.Add("Up\t" + e.KeyCode.ToString());
    e.Handled = true ;
}

void gkh_KeyDown(object sender, KeyEventArgs e) {
    lstLog.Items.Add("Down\t" + e.KeyCode.ToString());
    e.Handled = true ;
} 

Here I have chosen to watch for the A and B keys, and defined handlers for the KeyUp and KeyDown events that both log to a listbox called lstLog. So whenever the user presses the A or B keys, no matter what has focus, the application will be notified. Setting e.Handled to true makes it so no other notifications for this event go out, in the sample, this effectively stops the user from typing an A or B. This can be useful in ensuring that key combinations are not also typed out when used.

You can add hooks for as many keys as you would like, just add them like above. Don't get frustrated if you add a hook for a key and it doesn't work, many of them, like Keys.Shift show up as other more specific keys, like Keys.LShiftKey or Keys.RShiftKey. Keys.Alt shows up as Keys.LMenu or Keys.RMenu, Keys.Control shows up as Keys.LControl or Keys.RControl, just to name a few.

If you would like to hook or unhook the keyboard hook at any point, just call your globalKeyboardHook's hook and unhook methods, like so:

//unhook
gkh.unhook() 
//set the hook again
gkh.hook() 

Points of Interest

The bulk of the work in this code is done in the globalKeyboardHook class, although it is a fairly simple piece of code itself. The hardest part of doing this was finding the correct parameters for SetWindowsHookEx.

[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx
    (int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);

The parameters were worked out to be:

IntPtr hInstance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookProc, hInstance, 0);

The first parameter WH_KEYBOARD_LL is just saying that we want to hook the low level keyboard events, hookProc is the callback for the event, hInstance is a handle to User32.dll, where this event is first processed (I think). The last parameter is if you want to hook a specific thread, then you would just pass a thread id instead of using the hInstance.

History

  • 5/30/07 - First version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

StormySpike
Software Developer
United States United States
I currently work as a Software Engineer for a company in North Carolina, mainly working with C#.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionabout the Shift+A does not work Pinmemberlsh201113-Nov-11 21:07 
GeneralMy vote of 5 PinmemberAdelino Araújo10-Nov-11 3:03 
GeneralMy vote of 5 Pinmembermr_Prankster16-Aug-11 4:25 
QuestionCan it run without the .NET framework Pinmemberaces2723-Jul-11 21:02 
QuestionHow to send small letters with SHIFT key using SendKeys.Send? [modified] PinmemberShrish Pandit26-Mar-11 4:58 
GeneralKey Modifiers - Shift and Symbols Pinmemberaces2724-Mar-11 21:19 
Hi ,
Can you please give some light on how to use this to make is case sensitive and
also to detect symbols like " , .;: / ? etc.
 
Tried using ASCII value , but e.Modifier , e.Shift are always None.
 
And No Idea how to approach for the special symbol keys , and to get the ones Shift + numbers.
 
Minor modifications or guidelines , please provide any insight.
 
Thanks
 
Aces J
QuestionModifiers? Pinmemberf r i s c h24-Mar-11 11:09 
GeneralThanks! PinmemberAshenafiD.6-Feb-11 21:07 
Generalproblem with keyboardhook Pinmembermahboobeh mohamadi31-Jan-11 19:57 
QuestionUrgent Help NEEDED ! PinmemberMuthu7726-Jan-11 15:43 
GeneralWindows Service PinmemberMuthu7725-Jan-11 1:32 
GeneralMy vote of 5 PinmemberLevon Hovhannisyan21-Dec-10 5:49 
GeneralCallbackOnCollectedDelegate Exception PinmemberGrangeJM18-Dec-10 23:42 
GeneralAwesome! PinmemberKhoiTran197-Dec-10 17:45 
GeneralMy vote of 5 Pinmembermesuhas_sit7-Dec-10 16:52 
Generalctrl+alt+i Pinmemberpukino18030-Sep-10 10:13 
QuestionForeign characters? Pinmemberlvq68411-Sep-10 2:36 
GeneralAll keys PinmemberMember 724777630-Jul-10 5:35 
GeneralMy vote of 4 Pinmemberangelamerkel28-Jun-10 10:11 
GeneralMy vote of 1 PinmemberMember 356761318-Jun-10 1:38 
QuestionKey combination like CTRL+ALT+A? Pinmemberuhcafigdc4-Jun-10 9:03 
General[My vote of 2] Sorry not perfect... Pinmemberjohannesnestler25-May-10 23:50 
GeneralI get an error.... Pinmembermoni9425-May-10 0:42 
GeneralStrange problem concernign Arrow Keys [modified] Pinmembermuff997-Apr-10 1:28 
GeneralOverride F1 PinmemberFullmetal9901229-Mar-10 8:24 
GeneralApp locks up PinmemberFullmetal9901228-Mar-10 10:41 
GeneralKeyboard cant type! PinmemberBuggingMe22-Mar-10 10:57 
GeneralEXCELLENT! [modified] Pinmemberalexis410-Dec-09 9:05 
GeneralSystem.NullReferenceException PinmemberMariusUt1-Dec-09 8:27 
GeneralExample worked, but in my program the most bizzare error... PinmemberPhill6425-Nov-09 2:11 
GeneralCallback Error PinmemberVoulnet29-Oct-09 5:38 
GeneralGreat PinmemberRavenet9-Oct-09 7:24 
GeneralAlt + Q Pinmembera.xyz.b.16-Jul-09 7:40 
GeneralStops Capturing Keys PinmemberNate Shoffner24-May-09 12:23 
Questiontransfor it to wpf Pinmembersonicred2-Apr-09 1:09 
Generalunhook does not work, and when i capture the keyboard you cant type :( Pinmembermysquad13-Mar-09 5:26 
GeneralMDA error garbage collected delegate PinmemberAzraelKans2-Feb-09 13:26 
QuestionHow to use this for capturing all the keys? PinmemberMember 475432628-Jan-09 9:46 
GeneralNot capturing after random number of key strokes ! PinmemberMember 475432611-Jan-09 20:38 
GeneralMy vote of 1 PinmemberMember 407286520-Dec-08 8:29 
GeneralMy vote of 1 PinmemberMember 407286520-Dec-08 7:00 
GeneralReplace keystroke with another key PinmemberMember 56468673-Nov-08 5:51 
GeneralClarion MDI child window in C# PinmemberNino Mrdjen22-Oct-08 23:37 
GeneralNullReferenceException for SetWindowsHookEx PinmemberWayne Walter19-Oct-08 17:34 
GeneralHooked Keys cannot be used Pinmembersashdude8-Aug-08 8:16 
QuestionHow do I do it without forms? Pinmemberdjcouture29-Jul-08 5:06 
QuestionHow to use HookedKeys.addrange? PinmemberQSE15-May-08 9:09 
QuestionHow disabled Win Key PinmemberASysSolvers3-Apr-08 20:01 
QuestionMissing Code and Examples? PinmemberMember 361497712-Dec-07 9:44 
Questionkey combination Pinmemberjosephlawrencecarpio16-Sep-07 17:47 
GeneralThanks PinmemberNasenbaaer24-Jul-07 6:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130617.1 | Last Updated 30 May 2007
Article Copyright 2007 by StormySpike
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid