Click here to Skip to main content
12,888,825 members (49,917 online)
Click here to Skip to main content
Add your own
alternative version


150 bookmarked
Posted 30 May 2007

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


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

BugWill not pass modifiers into the KeyEventHandler method Pin
Joshua Parnell6-Jan-17 0:34
memberJoshua Parnell6-Jan-17 0:34 
AnswerRe: Will not pass modifiers into the KeyEventHandler method Pin
Joshua Parnell6-Jan-17 6:47
memberJoshua Parnell6-Jan-17 6:47 
QuestionCraching if key was long pressed and more Pin
Matt Grunig8-Nov-16 16:06
memberMatt Grunig8-Nov-16 16:06 
Questionhow do i detect if only one of the keys Pin
Member 1255194217-Jun-16 5:51
memberMember 1255194217-Jun-16 5:51 
Questiondisble ctrl+alt+del Pin
Member 123719125-Mar-16 10:27
memberMember 123719125-Mar-16 10:27 
AnswerRe: disble ctrl+alt+del Pin
Member 1224827127-Apr-16 3:45
memberMember 1224827127-Apr-16 3:45 
QuestionEvents fire only when app window on focus (only none letters fires when not focused) Pin
Member 830794027-Apr-15 8:59
memberMember 830794027-Apr-15 8:59 
GeneralVery Good job bro Pin
HelloHelloRain26-Nov-14 14:39
memberHelloHelloRain26-Nov-14 14:39 
QuestionBeginner Problem Pin
Member 1108671516-Sep-14 13:57
memberMember 1108671516-Sep-14 13:57 
QuestionAny solution yet for the problem when pressing same key after few times it stop and not responding anymore ? Pin
chocolade16-Sep-14 10:40
memberchocolade16-Sep-14 10:40 
GeneralMy vote of 5 Pin
Member 1035479628-Jul-14 22:24
memberMember 1035479628-Jul-14 22:24 
GeneralRe: My vote of 5 Pin
Member 982879326-Aug-14 1:46
memberMember 982879326-Aug-14 1:46 
QuestionUsing KeyboardHooks while Timer is active Pin
Paul Anuschek5-May-14 7:23
memberPaul Anuschek5-May-14 7:23 
AnswerRe: Using KeyboardHooks while Timer is active Pin
Joshua Parnell6-Jan-17 3:23
memberJoshua Parnell6-Jan-17 3:23 
QuestionCombination Pin
sdcdscs23-Mar-14 2:12
membersdcdscs23-Mar-14 2:12 
QuestionGreat job Pin
sunke_c#24-Nov-13 16:12
membersunke_c#24-Nov-13 16:12 
QuestionCallback on collected Delegate? Pin
banerjeedebasish17-Oct-13 12:53
memberbanerjeedebasish17-Oct-13 12:53 
GeneralThis worked like a charm Pin
Member 102628569-Sep-13 11:12
memberMember 102628569-Sep-13 11:12 
QuestionClean use Pin
AnotherKen26-May-13 16:42
memberAnotherKen26-May-13 16:42 
AnswerRe: Clean use Pin
AnotherKen29-May-13 12:02
memberAnotherKen29-May-13 12:02 
GeneralMy vote of 5 Pin
AnotherKen15-May-13 20:52
memberAnotherKen15-May-13 20:52 
QuestionUsing this class in a WPF application Pin
VSZM14-Apr-13 12:47
memberVSZM14-Apr-13 12:47 
QuestionATT: Developer of (Simple-C-Global-Low-Level-Keyboard-Hook) Pin
DJBruteForce5-Apr-13 2:17
memberDJBruteForce5-Apr-13 2:17 
BugA callback was made on a garbage collected delegate of type .... Pin
Member 41208549-Jan-13 22:52
memberMember 41208549-Jan-13 22:52 
GeneralRe: A callback was made on a garbage collected delegate of type .... Pin
AnotherKen29-May-13 11:58
memberAnotherKen29-May-13 11:58 
GeneralRe: A callback was made on a garbage collected delegate of type .... Pin
banerjeedebasish17-Oct-13 13:25
memberbanerjeedebasish17-Oct-13 13:25 
GeneralRe: A callback was made on a garbage collected delegate of type .... Pin
sunke_c#24-Nov-13 20:11
membersunke_c#24-Nov-13 20:11 
GeneralRe: A callback was made on a garbage collected delegate of type .... Pin
retsd22-Apr-17 9:52
memberretsd22-Apr-17 9:52 
BugI need help Pin
Member 97217003-Jan-13 1:18
memberMember 97217003-Jan-13 1:18 
GeneralRe: I need help Pin
Jean Meyblum9-Jan-13 20:49
memberJean Meyblum9-Jan-13 20:49 
GeneralThx for Nice Article Pin
iHUPPz Rwt7-Sep-12 8:26
memberiHUPPz Rwt7-Sep-12 8:26 
QuestionAnti Virus - Because of Set Windows Hook Pin
aces277-Sep-12 3:50
memberaces277-Sep-12 3:50 
AnswerRe: Anti Virus - Because of Set Windows Hook Pin
Eddy Vluggen4-Jun-14 11:11
professionalEddy Vluggen4-Jun-14 11:11 
Question32 Bit / 64 Bit Pin
aces277-Sep-12 3:47
memberaces277-Sep-12 3:47 
Questionhow to avoid repeated pressing of a key Pin
IgorBogomolov6-Sep-12 11:16
memberIgorBogomolov6-Sep-12 11:16 
AnswerRe: how to avoid repeated pressing of a key Pin
AnotherKen28-May-13 20:03
memberAnotherKen28-May-13 20:03 
GeneralRe: how to avoid repeated pressing of a key Pin
irobot_22911-Aug-13 0:31
memberirobot_22911-Aug-13 0:31 
GeneralRe: how to avoid repeated pressing of a key Pin
AnotherKen11-Aug-13 8:08
memberAnotherKen11-Aug-13 8:08 
GeneralMy vote of 5 Pin
IgorBogomolov6-Sep-12 11:13
memberIgorBogomolov6-Sep-12 11:13 
Bugnot stable Pin
Martype2.028-Aug-12 22:54
memberMartype2.028-Aug-12 22:54 
GeneralAdding Modifier Key Handling using GetKeyState Pin
jonegerton20-Aug-12 21:55
memberjonegerton20-Aug-12 21:55 
Modifier handling can be added to work on the global hook by adding GetKeyState to the globalKeyboardHook class.

This can be done in such a way the KeyEventArgs passed in the events have their Control, Alt and Shift properties correctly set.

I've blogged on how to do this, including a full version of globalKeyboardHook with the extra code built in, here.
GeneralRe: Adding Modifier Key Handling using GetKeyState Pin
VSZM14-Apr-13 13:22
memberVSZM14-Apr-13 13:22 
GeneralRe: Adding Modifier Key Handling using GetKeyState Pin
Member 104003745-Mar-14 5:59
memberMember 104003745-Mar-14 5:59 
QuestionHow to hook combination of keys, not one by one ? Pin
NithrouS1-Aug-12 12:01
memberNithrouS1-Aug-12 12:01 
AnswerRe: How to hook combination of keys, not one by one ? Pin
AnotherKen26-May-13 16:19
memberAnotherKen26-May-13 16:19 
GeneralMy vote of 4 Pin
Burak Tunçbilek27-Jul-12 10:06
memberBurak Tunçbilek27-Jul-12 10:06 
Suggestionsuggestion for improvement Pin
Christoph Strehle12-May-12 7:15
memberChristoph Strehle12-May-12 7:15 
Questionabout the Shift+A does not work Pin
lsh201113-Nov-11 21:07
memberlsh201113-Nov-11 21:07 
GeneralMy vote of 5 Pin
Adelino Araújo10-Nov-11 3:03
memberAdelino Araújo10-Nov-11 3:03 
GeneralMy vote of 5 Pin
mr_Prankster16-Aug-11 4:25
membermr_Prankster16-Aug-11 4:25 

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