Click here to Skip to main content
11,645,033 members (63,281 online)
Click here to Skip to main content

A Simple C# Global Low Level Keyboard Hook

, 30 May 2007 CPOL 413K 35.2K 144
Rate this:
Please Sign up or sign in to vote.
A simple description and sample of creating a global low level keyboard hook in C#
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)

Share

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#.

You may also be interested in...

Comments and Discussions

 
Generalproblem with keyboardhook Pin
mahboobeh mohamadi31-Jan-11 19:57
membermahboobeh mohamadi31-Jan-11 19:57 
QuestionUrgent Help NEEDED ! Pin
Muthu7726-Jan-11 15:43
memberMuthu7726-Jan-11 15:43 
GeneralWindows Service Pin
Muthu7725-Jan-11 1:32
memberMuthu7725-Jan-11 1:32 
GeneralMy vote of 5 Pin
Levon Hovhannisyan21-Dec-10 5:49
memberLevon Hovhannisyan21-Dec-10 5:49 
GeneralCallbackOnCollectedDelegate Exception Pin
GrangeJM18-Dec-10 23:42
memberGrangeJM18-Dec-10 23:42 
GeneralRe: CallbackOnCollectedDelegate Exception Pin
mahboobeh mohamadi31-Jan-11 22:51
membermahboobeh mohamadi31-Jan-11 22:51 
GeneralRe: CallbackOnCollectedDelegate Exception Pin
Leye011-Apr-12 22:13
memberLeye011-Apr-12 22:13 
GeneralAwesome! Pin
KhoiTran197-Dec-10 17:45
memberKhoiTran197-Dec-10 17:45 
GeneralMy vote of 5 Pin
mesuhas_sit7-Dec-10 16:52
membermesuhas_sit7-Dec-10 16:52 
Generalctrl+alt+i Pin
pukino18030-Sep-10 10:13
memberpukino18030-Sep-10 10:13 
GeneralRe: ctrl+alt+i Pin
DungVinh12-Feb-12 23:48
memberDungVinh12-Feb-12 23:48 
QuestionForeign characters? Pin
lvq68411-Sep-10 2:36
memberlvq68411-Sep-10 2:36 
GeneralAll keys Pin
Member 724777630-Jul-10 5:35
memberMember 724777630-Jul-10 5:35 
GeneralRe: All keys Pin
jrbosch2-Jan-11 21:47
memberjrbosch2-Jan-11 21:47 
foreach (System.Windows.Forms.Keys item in Enum.GetValues(typeof(System.Windows.Forms.Keys)))
{
gkh.HookedKeys.Add(item);
}
GeneralMy vote of 4 Pin
angelamerkel28-Jun-10 10:11
memberangelamerkel28-Jun-10 10:11 
GeneralMy vote of 1 Pin
Member 356761318-Jun-10 1:38
memberMember 356761318-Jun-10 1:38 
QuestionKey combination like CTRL+ALT+A? Pin
uhcafigdc4-Jun-10 9:03
memberuhcafigdc4-Jun-10 9:03 
General[My vote of 2] Sorry not perfect... Pin
johannesnestler25-May-10 23:50
memberjohannesnestler25-May-10 23:50 
GeneralRe: [My vote of 2] Sorry not perfect... Pin
VHong99923-Sep-11 16:45
memberVHong99923-Sep-11 16:45 
GeneralI get an error.... Pin
moni9425-May-10 0:42
membermoni9425-May-10 0:42 
GeneralRe: I get an error.... Pin
mahboobeh mohamadi31-Jan-11 20:08
membermahboobeh mohamadi31-Jan-11 20:08 
GeneralStrange problem concernign Arrow Keys [modified] Pin
muff997-Apr-10 1:28
membermuff997-Apr-10 1:28 
GeneralOverride F1 Pin
Fullmetal9901229-Mar-10 8:24
memberFullmetal9901229-Mar-10 8:24 
GeneralApp locks up Pin
Fullmetal9901228-Mar-10 10:41
memberFullmetal9901228-Mar-10 10:41 
GeneralKeyboard cant type! Pin
BuggingMe22-Mar-10 10:57
memberBuggingMe22-Mar-10 10:57 
GeneralRe: Keyboard cant type! Pin
StormySpike23-Mar-10 14:10
memberStormySpike23-Mar-10 14:10 
GeneralEXCELLENT! [modified] Pin
alexis410-Dec-09 9:05
memberalexis410-Dec-09 9:05 
GeneralSystem.NullReferenceException Pin
MariusUt1-Dec-09 8:27
memberMariusUt1-Dec-09 8:27 
GeneralExample worked, but in my program the most bizzare error... Pin
Phill6425-Nov-09 2:11
memberPhill6425-Nov-09 2:11 
GeneralRe: Example worked, but in my program the most bizzare error... Pin
Phill6425-Nov-09 10:30
memberPhill6425-Nov-09 10:30 
GeneralCallback Error Pin
Voulnet29-Oct-09 5:38
memberVoulnet29-Oct-09 5:38 
GeneralRe: Callback Error Pin
Voulnet29-Oct-09 6:32
memberVoulnet29-Oct-09 6:32 
GeneralRe: Callback Error Pin
patawic27-Nov-10 19:59
memberpatawic27-Nov-10 19:59 
GeneralRe: Callback Error Pin
patawic27-Nov-10 20:02
memberpatawic27-Nov-10 20:02 
GeneralGreat Pin
Ravenet9-Oct-09 7:24
memberRavenet9-Oct-09 7:24 
GeneralAlt + Q Pin
a.xyz.b.16-Jul-09 7:40
membera.xyz.b.16-Jul-09 7:40 
GeneralStops Capturing Keys Pin
Nate Shoffner24-May-09 12:23
memberNate Shoffner24-May-09 12:23 
GeneralRe: Stops Capturing Keys Pin
berni270416-Oct-09 3:27
memberberni270416-Oct-09 3:27 
Questiontransfor it to wpf Pin
sonicred2-Apr-09 1:09
membersonicred2-Apr-09 1:09 
AnswerRe: transfor it to wpf Pin
StormySpike2-Apr-09 7:55
memberStormySpike2-Apr-09 7:55 
GeneralRe: transfor it to wpf Pin
sonicred3-Apr-09 13:48
membersonicred3-Apr-09 13:48 
GeneralRe: transfor it to wpf Pin
StormySpike20-Apr-09 13:47
memberStormySpike20-Apr-09 13:47 
GeneralRe: transfor it to wpf Pin
panoylhs22-Sep-09 4:42
memberpanoylhs22-Sep-09 4:42 
Generalunhook does not work, and when i capture the keyboard you cant type :( Pin
mysquad13-Mar-09 5:26
membermysquad13-Mar-09 5:26 
GeneralRe: unhook does not work, and when i capture the keyboard you cant type :( Pin
StormySpike13-Mar-09 14:39
memberStormySpike13-Mar-09 14:39 
GeneralRe: unhook does not work, and when i capture the keyboard you cant type :( Pin
Phill6425-Nov-09 10:38
memberPhill6425-Nov-09 10:38 
GeneralMDA error garbage collected delegate Pin
AzraelKans2-Feb-09 13:26
memberAzraelKans2-Feb-09 13:26 
GeneralRe: MDA error garbage collected delegate Pin
StormySpike13-Mar-09 14:45
memberStormySpike13-Mar-09 14:45 
GeneralRe: MDA error garbage collected delegate Pin
weso18-Aug-09 15:54
memberweso18-Aug-09 15:54 
GeneralRe: MDA error garbage collected delegate Pin
Member 25165064-Oct-09 10:31
memberMember 25165064-Oct-09 10:31 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150731.1 | Last Updated 30 May 2007
Article Copyright 2007 by StormySpike
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid