Click here to Skip to main content
13,247,398 members (57,259 online)
Click here to Skip to main content
Add your own
alternative version


153 bookmarked
Posted 30 May 2007

A Simple C# Global Low Level Keyboard Hook

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


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.


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

//set the hook again

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.

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.


  • 5/30/07 - First version


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


About the Author

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

GeneralMy vote of 5 Pin
IgorBogomolov6-Sep-12 12:13
memberIgorBogomolov6-Sep-12 12:13 
Bugnot stable Pin
Martype2.028-Aug-12 23:54
memberMartype2.028-Aug-12 23:54 
GeneralAdding Modifier Key Handling using GetKeyState Pin
jonegerton20-Aug-12 22:55
memberjonegerton20-Aug-12 22:55 
GeneralRe: Adding Modifier Key Handling using GetKeyState Pin
VSZM14-Apr-13 14:22
memberVSZM14-Apr-13 14:22 
GeneralRe: Adding Modifier Key Handling using GetKeyState Pin
Member 104003745-Mar-14 6:59
memberMember 104003745-Mar-14 6:59 
QuestionHow to hook combination of keys, not one by one ? Pin
NithrouS1-Aug-12 13:01
memberNithrouS1-Aug-12 13:01 
AnswerRe: How to hook combination of keys, not one by one ? Pin
AnotherKen26-May-13 17:19
memberAnotherKen26-May-13 17:19 
GeneralMy vote of 4 Pin
Burak Tunçbilek27-Jul-12 11:06
memberBurak Tunçbilek27-Jul-12 11:06 
Suggestionsuggestion for improvement Pin
Christoph Strehle12-May-12 8:15
memberChristoph Strehle12-May-12 8:15 
Questionabout the Shift+A does not work Pin
lsh201113-Nov-11 22:07
memberlsh201113-Nov-11 22:07 
GeneralMy vote of 5 Pin
Adelino Araújo10-Nov-11 4:03
memberAdelino Araújo10-Nov-11 4:03 
GeneralMy vote of 5 Pin
mr_Prankster16-Aug-11 5:25
membermr_Prankster16-Aug-11 5:25 
QuestionCan it run without the .NET framework Pin
aces2723-Jul-11 22:02
memberaces2723-Jul-11 22:02 
QuestionHow to send small letters with SHIFT key using SendKeys.Send? [modified] Pin
Shrish Pandit26-Mar-11 5:58
memberShrish Pandit26-Mar-11 5:58 
I am unable to send small letters using SendKeys.Send() with SHIFT modifier key pressed. My app needs (for example) if the user presses K button "a" should be sent and if he presses SHIFT+K, "b" should be sent. The code is:

void gkh_KeyDown(object sender, KeyEventArgs e)
	if (e.KeyCode == Keys.K)
		if (Control.ModifierKeys == Keys.Shift)
        e.Handled == true;   

But it sends "B" (Capital letter) instead of "b", that is the SHIFT key changes the sent keystroke "b" to uppercase. This happens even after adding Keys.Shift to the hook.

I tried many approaches including using e.SupressKeyPress, SendKeys("b".toLower()) and putting above code in KeyUp event but in vein.

Pls help me, I am very frustated, my application developement is struck at this point.
modified on Saturday, March 26, 2011 11:19 AM

AnswerRe: How to send small letters with SHIFT key using SendKeys.Send? [modified] Pin
AnotherKen26-May-13 17:33
memberAnotherKen26-May-13 17:33 
GeneralKey Modifiers - Shift and Symbols Pin
aces2724-Mar-11 22:19
memberaces2724-Mar-11 22:19 
AnswerRe: Key Modifiers - Shift and Symbols [modified] Pin
Shrish Pandit25-Mar-11 16:52
memberShrish Pandit25-Mar-11 16:52 
QuestionModifiers? Pin
f r i s c h24-Mar-11 12:09
memberf r i s c h24-Mar-11 12:09 
AnswerRe: Modifiers? Pin
aces2724-Mar-11 22:21
memberaces2724-Mar-11 22:21 
GeneralThanks! Pin
AshenafiD.6-Feb-11 22:07
memberAshenafiD.6-Feb-11 22:07 
Generalproblem with keyboardhook Pin
mahboobeh mohamadi31-Jan-11 20:57
membermahboobeh mohamadi31-Jan-11 20:57 
QuestionUrgent Help NEEDED ! Pin
Muthu7726-Jan-11 16:43
memberMuthu7726-Jan-11 16:43 
GeneralWindows Service Pin
Muthu7725-Jan-11 2:32
memberMuthu7725-Jan-11 2:32 
GeneralMy vote of 5 Pin
Levon Hovhannisyan21-Dec-10 6:49
memberLevon Hovhannisyan21-Dec-10 6:49 
GeneralCallbackOnCollectedDelegate Exception Pin
GrangeJM19-Dec-10 0:42
memberGrangeJM19-Dec-10 0:42 
GeneralRe: CallbackOnCollectedDelegate Exception Pin
mahboobeh mohamadi31-Jan-11 23:51
membermahboobeh mohamadi31-Jan-11 23:51 
GeneralRe: CallbackOnCollectedDelegate Exception Pin
Leye011-Apr-12 23:13
memberLeye011-Apr-12 23:13 
GeneralAwesome! Pin
KhoiTran197-Dec-10 18:45
memberKhoiTran197-Dec-10 18:45 
GeneralMy vote of 5 Pin
mesuhas_sit7-Dec-10 17:52
membermesuhas_sit7-Dec-10 17:52 
Generalctrl+alt+i Pin
pukino18030-Sep-10 11:13
memberpukino18030-Sep-10 11:13 
GeneralRe: ctrl+alt+i Pin
DungVinh13-Feb-12 0:48
memberDungVinh13-Feb-12 0:48 
QuestionForeign characters? Pin
lvq68411-Sep-10 3:36
memberlvq68411-Sep-10 3:36 
GeneralAll keys Pin
Member 724777630-Jul-10 6:35
memberMember 724777630-Jul-10 6:35 
GeneralRe: All keys Pin
jrbosch2-Jan-11 22:47
memberjrbosch2-Jan-11 22:47 
GeneralMy vote of 4 Pin
angelamerkel28-Jun-10 11:11
memberangelamerkel28-Jun-10 11:11 
GeneralMy vote of 1 Pin
Member 356761318-Jun-10 2:38
memberMember 356761318-Jun-10 2:38 
QuestionKey combination like CTRL+ALT+A? Pin
uhcafigdc4-Jun-10 10:03
memberuhcafigdc4-Jun-10 10:03 
General[My vote of 2] Sorry not perfect... Pin
johannesnestler26-May-10 0:50
memberjohannesnestler26-May-10 0:50 
GeneralRe: [My vote of 2] Sorry not perfect... Pin
VHong99923-Sep-11 17:45
memberVHong99923-Sep-11 17:45 
GeneralI get an error.... Pin
moni9425-May-10 1:42
membermoni9425-May-10 1:42 
GeneralRe: I get an error.... Pin
mahboobeh mohamadi31-Jan-11 21:08
membermahboobeh mohamadi31-Jan-11 21:08 
GeneralStrange problem concernign Arrow Keys [modified] Pin
muff997-Apr-10 2:28
membermuff997-Apr-10 2:28 
GeneralOverride F1 Pin
Fullmetal9901229-Mar-10 9:24
memberFullmetal9901229-Mar-10 9:24 
GeneralApp locks up Pin
Fullmetal9901228-Mar-10 11:41
memberFullmetal9901228-Mar-10 11:41 
GeneralKeyboard cant type! Pin
BuggingMe22-Mar-10 11:57
memberBuggingMe22-Mar-10 11:57 
GeneralRe: Keyboard cant type! Pin
StormySpike23-Mar-10 15:10
memberStormySpike23-Mar-10 15:10 
GeneralEXCELLENT! [modified] Pin
alexis410-Dec-09 10:05
memberalexis410-Dec-09 10:05 
GeneralSystem.NullReferenceException Pin
MariusUt1-Dec-09 9:27
memberMariusUt1-Dec-09 9:27 
GeneralExample worked, but in my program the most bizzare error... Pin
Phill6425-Nov-09 3:11
memberPhill6425-Nov-09 3:11 
GeneralRe: Example worked, but in my program the most bizzare error... Pin
Phill6425-Nov-09 11:30
memberPhill6425-Nov-09 11:30 

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

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

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