Click here to Skip to main content
11,412,516 members (65,985 online)
Click here to Skip to main content

A Simple C# Global Low Level Keyboard Hook

, 30 May 2007 CPOL
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#.

Comments and Discussions

 
GeneralVery Good job bro Pin
HelloHelloRain at 26-Nov-14 15:39
memberHelloHelloRain26-Nov-14 15:39 
QuestionBeginner Problem Pin
Member 11086715 at 16-Sep-14 14:57
memberMember 1108671516-Sep-14 14:57 
QuestionAny solution yet for the problem when pressing same key after few times it stop and not responding anymore ? Pin
chocolade at 16-Sep-14 11:40
memberchocolade16-Sep-14 11:40 
GeneralMy vote of 5 Pin
Member 10354796 at 28-Jul-14 23:24
memberMember 1035479628-Jul-14 23:24 
GeneralRe: My vote of 5 Pin
Member 9828793 at 26-Aug-14 2:46
memberMember 982879326-Aug-14 2:46 
QuestionUsing KeyboardHooks while Timer is active Pin
Paul Anuschek at 5-May-14 8:23
memberPaul Anuschek5-May-14 8:23 
QuestionCombination Pin
sdcdscs at 23-Mar-14 3:12
membersdcdscs23-Mar-14 3:12 
QuestionGreat job Pin
sunke_c# at 24-Nov-13 17:12
membersunke_c#24-Nov-13 17:12 
QuestionCallback on collected Delegate? [modified] Pin
banerjeedebasish at 17-Oct-13 13:53
memberbanerjeedebasish17-Oct-13 13:53 
GeneralThis worked like a charm Pin
Member 10262856 at 9-Sep-13 12:12
memberMember 102628569-Sep-13 12:12 
QuestionClean use Pin
AnotherKen at 26-May-13 17:42
memberAnotherKen26-May-13 17:42 
AnswerRe: Clean use Pin
AnotherKen at 29-May-13 13:02
memberAnotherKen29-May-13 13:02 
GeneralMy vote of 5 Pin
AnotherKen at 15-May-13 21:52
memberAnotherKen15-May-13 21:52 
QuestionUsing this class in a WPF application Pin
VSZM at 14-Apr-13 13:47
memberVSZM14-Apr-13 13:47 
QuestionATT: Developer of (Simple-C-Global-Low-Level-Keyboard-Hook) Pin
DJBruteForce at 5-Apr-13 3:17
memberDJBruteForce5-Apr-13 3:17 
BugA callback was made on a garbage collected delegate of type .... Pin
Member 4120854 at 9-Jan-13 23:52
memberMember 41208549-Jan-13 23:52 
GeneralRe: A callback was made on a garbage collected delegate of type .... Pin
AnotherKen at 29-May-13 12:58
memberAnotherKen29-May-13 12:58 
GeneralRe: A callback was made on a garbage collected delegate of type .... Pin
banerjeedebasish at 17-Oct-13 14:25
memberbanerjeedebasish17-Oct-13 14:25 
GeneralRe: A callback was made on a garbage collected delegate of type .... Pin
sunke_c# at 24-Nov-13 21:11
membersunke_c#24-Nov-13 21:11 
BugI need help Pin
Member 9721700 at 3-Jan-13 2:18
memberMember 97217003-Jan-13 2:18 
GeneralRe: I need help Pin
Jean Meyblum at 9-Jan-13 21:49
memberJean Meyblum9-Jan-13 21:49 
GeneralThx for Nice Article Pin
iHUPPz Rwt at 7-Sep-12 9:26
memberiHUPPz Rwt7-Sep-12 9:26 
QuestionAnti Virus - Because of Set Windows Hook Pin
aces27 at 7-Sep-12 4:50
memberaces277-Sep-12 4:50 
AnswerRe: Anti Virus - Because of Set Windows Hook Pin
Eddy Vluggen at 4-Jun-14 12:11
professionalEddy Vluggen4-Jun-14 12:11 
Question32 Bit / 64 Bit Pin
aces27 at 7-Sep-12 4:47
memberaces277-Sep-12 4:47 
Questionhow to avoid repeated pressing of a key Pin
IgorBogomolov at 6-Sep-12 12:16
memberIgorBogomolov6-Sep-12 12:16 
AnswerRe: how to avoid repeated pressing of a key Pin
AnotherKen at 28-May-13 21:03
memberAnotherKen28-May-13 21:03 
GeneralRe: how to avoid repeated pressing of a key Pin
irobot_229 at 11-Aug-13 1:31
memberirobot_22911-Aug-13 1:31 
GeneralRe: how to avoid repeated pressing of a key Pin
AnotherKen at 11-Aug-13 9:08
memberAnotherKen11-Aug-13 9:08 
GeneralMy vote of 5 Pin
IgorBogomolov at 6-Sep-12 12:13
memberIgorBogomolov6-Sep-12 12:13 
Bugnot stable Pin
Martype2.0 at 28-Aug-12 23:54
memberMartype2.028-Aug-12 23:54 
GeneralAdding Modifier Key Handling using GetKeyState Pin
jonegerton at 20-Aug-12 22:55
memberjonegerton20-Aug-12 22:55 
GeneralRe: Adding Modifier Key Handling using GetKeyState Pin
VSZM at 14-Apr-13 14:22
memberVSZM14-Apr-13 14:22 
GeneralRe: Adding Modifier Key Handling using GetKeyState Pin
Member 10400374 at 5-Mar-14 6:59
memberMember 104003745-Mar-14 6:59 
QuestionHow to hook combination of keys, not one by one ? Pin
NithrouS at 1-Aug-12 13:01
memberNithrouS1-Aug-12 13:01 
AnswerRe: How to hook combination of keys, not one by one ? Pin
AnotherKen at 26-May-13 17:19
memberAnotherKen26-May-13 17:19 
GeneralMy vote of 4 Pin
Burak Tunçbilek at 27-Jul-12 11:06
memberBurak Tunçbilek27-Jul-12 11:06 
Suggestionsuggestion for improvement Pin
Christoph Strehle at 12-May-12 8:15
memberChristoph Strehle12-May-12 8:15 
Questionabout the Shift+A does not work Pin
lsh2011 at 13-Nov-11 22:07
memberlsh201113-Nov-11 22:07 
GeneralMy vote of 5 Pin
Adelino Araújo at 10-Nov-11 4:03
memberAdelino Araújo10-Nov-11 4:03 
GeneralMy vote of 5 Pin
mr_Prankster at 16-Aug-11 5:25
membermr_Prankster16-Aug-11 5:25 
Thanks)
QuestionCan it run without the .NET framework Pin
aces27 at 23-Jul-11 22:02
memberaces2723-Jul-11 22:02 
QuestionHow to send small letters with SHIFT key using SendKeys.Send? [modified] Pin
Shrish Pandit at 26-Mar-11 5:58
memberShrish Pandit26-Mar-11 5:58 
AnswerRe: How to send small letters with SHIFT key using SendKeys.Send? [modified] Pin
AnotherKen at 26-May-13 17:33
memberAnotherKen26-May-13 17:33 
GeneralKey Modifiers - Shift and Symbols Pin
aces27 at 24-Mar-11 22:19
memberaces2724-Mar-11 22:19 
AnswerRe: Key Modifiers - Shift and Symbols [modified] Pin
Shrish Pandit at 25-Mar-11 16:52
memberShrish Pandit25-Mar-11 16:52 
QuestionModifiers? Pin
f r i s c h at 24-Mar-11 12:09
memberf r i s c h24-Mar-11 12:09 
AnswerRe: Modifiers? Pin
aces27 at 24-Mar-11 22:21
memberaces2724-Mar-11 22:21 
GeneralThanks! Pin
AshenafiD. at 6-Feb-11 22:07
memberAshenafiD.6-Feb-11 22:07 
Generalproblem with keyboardhook Pin
mahboobeh mohamadi at 31-Jan-11 20:57
membermahboobeh mohamadi31-Jan-11 20:57 

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
Web04 | 2.8.150427.1 | Last Updated 30 May 2007
Article Copyright 2007 by StormySpike
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid