Click here to Skip to main content
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


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

Comments and Discussions

QuestionForeign characters? Pinmemberlvq68411-Sep-10 3:36 
GeneralAll keys PinmemberMember 724777630-Jul-10 6:35 
GeneralRe: All keys Pinmemberjrbosch2-Jan-11 22:47 
GeneralMy vote of 4 Pinmemberangelamerkel28-Jun-10 11:11 
GeneralMy vote of 1 PinmemberMember 356761318-Jun-10 2:38 
QuestionKey combination like CTRL+ALT+A? Pinmemberuhcafigdc4-Jun-10 10:03 
General[My vote of 2] Sorry not perfect... Pinmemberjohannesnestler26-May-10 0:50 
GeneralRe: [My vote of 2] Sorry not perfect... PinmemberVHong99923-Sep-11 17:45 
GeneralI get an error.... Pinmembermoni9425-May-10 1:42 
GeneralRe: I get an error.... Pinmembermahboobeh mohamadi31-Jan-11 21:08 
GeneralStrange problem concernign Arrow Keys [modified] Pinmembermuff997-Apr-10 2:28 
GeneralOverride F1 PinmemberFullmetal9901229-Mar-10 9:24 
GeneralApp locks up PinmemberFullmetal9901228-Mar-10 11:41 
GeneralKeyboard cant type! PinmemberBuggingMe22-Mar-10 11:57 
Hi, i'm trying to make my program pick up any key and write it in a text file when i press F6, then, i want the text file to be read and all the text from it put into a TextBox on the form by pressing F7. I've looked at numerous posts such as the one with the _hookAll thing, but when i type ANYTHING on a text field with this function, nothing happens. the text doesnt even appear.

I'm making a spammer (for experimental reasons) and everything works. I want the user to be able to set a new message without going back to the Form (by pressing F6 to activate, F7 to set).

I might not even have to use streamwriter/reader to do this, it just seems an easier option for me.

So can someone tell me why and how to stop the program disabling my keyboard?

GeneralRe: Keyboard cant type! PinmemberStormySpike23-Mar-10 15:10 
GeneralEXCELLENT! [modified] Pinmemberalexis410-Dec-09 10:05 
GeneralSystem.NullReferenceException PinmemberMariusUt1-Dec-09 9:27 
GeneralExample worked, but in my program the most bizzare error... PinmemberPhill6425-Nov-09 3:11 
GeneralRe: Example worked, but in my program the most bizzare error... PinmemberPhill6425-Nov-09 11:30 
GeneralCallback Error PinmemberVoulnet29-Oct-09 6:38 
GeneralRe: Callback Error PinmemberVoulnet29-Oct-09 7:32 
GeneralRe: Callback Error Pinmemberpatawic27-Nov-10 20:59 
GeneralRe: Callback Error Pinmemberpatawic27-Nov-10 21:02 
GeneralGreat PinmemberRavenet9-Oct-09 8:24 
GeneralAlt + Q 8:40 
GeneralStops Capturing Keys PinmemberNate Shoffner24-May-09 13:23 
GeneralRe: Stops Capturing Keys Pinmemberberni270416-Oct-09 4:27 
Questiontransfor it to wpf Pinmembersonicred2-Apr-09 2:09 
AnswerRe: transfor it to wpf PinmemberStormySpike2-Apr-09 8:55 
GeneralRe: transfor it to wpf Pinmembersonicred3-Apr-09 14:48 
GeneralRe: transfor it to wpf PinmemberStormySpike20-Apr-09 14:47 
GeneralRe: transfor it to wpf Pinmemberpanoylhs22-Sep-09 5:42 
Generalunhook does not work, and when i capture the keyboard you cant type :( Pinmembermysquad13-Mar-09 6:26 
GeneralRe: unhook does not work, and when i capture the keyboard you cant type :( PinmemberStormySpike13-Mar-09 15:39 
GeneralRe: unhook does not work, and when i capture the keyboard you cant type :( PinmemberPhill6425-Nov-09 11:38 
GeneralMDA error garbage collected delegate PinmemberAzraelKans2-Feb-09 14:26 
GeneralRe: MDA error garbage collected delegate PinmemberStormySpike13-Mar-09 15:45 
GeneralRe: MDA error garbage collected delegate Pinmemberweso18-Aug-09 16:54 
GeneralRe: MDA error garbage collected delegate PinmemberMember 25165064-Oct-09 11:31 
GeneralRe: MDA error garbage collected delegate Pinmemberavihaydar1012-Oct-09 23:21 
GeneralRe: MDA error garbage collected delegate Pinmemberkendolew23-Oct-09 6:43 
QuestionHow to use this for capturing all the keys? PinmemberMember 475432628-Jan-09 10:46 
AnswerRe: How to use this for capturing all the keys? PinmemberStormySpike13-Mar-09 15:41 
AnswerRe: How to use this for capturing all the keys? Pinmemberjwainer6-Aug-09 15:33 
GeneralRe: How to use this for capturing all the keys? PinmemberBuggingMe22-Mar-10 7:54 
AnswerRe: How to use this for capturing all the keys? PinmemberShrish Pandit25-Mar-11 16:51 
GeneralNot capturing after random number of key strokes ! PinmemberMember 475432611-Jan-09 21:38 
GeneralMy vote of 1 PinmemberMember 407286520-Dec-08 9:29 
GeneralMy vote of 1 PinmemberMember 407286520-Dec-08 8:00 
GeneralReplace keystroke with another key PinmemberMember 56468673-Nov-08 6:51 

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