Click here to Skip to main content
15,125,121 members
Articles / Programming Languages / C#
Posted 30 May 2007


169 bookmarked

A Simple C# Global Low Level Keyboard Hook

Rate me:
Please Sign up or sign in to vote.
4.90/5 (96 votes)
30 May 2007CPOL2 min read
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

GeneralNot capturing after random number of key strokes ! Pin
Member 475432611-Jan-09 21:38
MemberMember 475432611-Jan-09 21:38 
GeneralMy vote of 1 Pin
Member 407286520-Dec-08 9:29
MemberMember 407286520-Dec-08 9:29 
GeneralMy vote of 1 Pin
Member 407286520-Dec-08 8:00
MemberMember 407286520-Dec-08 8:00 
GeneralReplace keystroke with another key Pin
stormydaniels3-Nov-08 6:51
Memberstormydaniels3-Nov-08 6:51 
GeneralRe: Replace keystroke with another key Pin
StormySpike10-Nov-08 10:07
MemberStormySpike10-Nov-08 10:07 
GeneralClarion MDI child window in C# Pin
papacol23-Oct-08 0:37
Memberpapacol23-Oct-08 0:37 
GeneralRe: Clarion MDI child window in C# Pin
StormySpike10-Nov-08 10:12
MemberStormySpike10-Nov-08 10:12 
GeneralRe: Clarion MDI child window in C# Pin
papacol13-Nov-08 23:52
Memberpapacol13-Nov-08 23:52 
Thanks for your reply!

Could you tell me this then.. How can I start a clarion procedure/window with specifying it's parent (via handle passed from c#)?

Sorry for bothering you, but Clarion community is not very large and I already tried the newsgroups and googled my brains out Smile | :) So thanks for any help you can give, it's much appreciated!
GeneralNullReferenceException for SetWindowsHookEx Pin
Wayne Walter19-Oct-08 18:34
MemberWayne Walter19-Oct-08 18:34 
GeneralRe: NullReferenceException for SetWindowsHookEx Pin
Wayne Walter19-Oct-08 20:20
MemberWayne Walter19-Oct-08 20:20 
GeneralHooked Keys cannot be used Pin
sashdude8-Aug-08 9:16
Membersashdude8-Aug-08 9:16 
GeneralRe: Hooked Keys cannot be used Pin
Michaelwh8-Aug-08 11:32
MemberMichaelwh8-Aug-08 11:32 
QuestionHow do I do it without forms? Pin
djcouture29-Jul-08 6:06
Memberdjcouture29-Jul-08 6:06 
AnswerRe: How do I do it without forms? Pin
StormySpike9-Aug-08 6:18
MemberStormySpike9-Aug-08 6:18 
GeneralRe: How do I do it without forms? Pin
djcouture14-Aug-08 9:18
Memberdjcouture14-Aug-08 9:18 
QuestionHow to use HookedKeys.addrange? Pin
QSE15-May-08 10:09
MemberQSE15-May-08 10:09 
AnswerRe: How to use HookedKeys.addrange? Pin
StormySpike15-May-08 10:34
MemberStormySpike15-May-08 10:34 
GeneralRe: How to use HookedKeys.addrange? Pin
QSE15-May-08 12:56
MemberQSE15-May-08 12:56 
GeneralRe: How to use HookedKeys.addrange? Pin
BuggingMe22-Mar-10 8:07
MemberBuggingMe22-Mar-10 8:07 
QuestionHow disabled Win Key Pin
ASysSolvers3-Apr-08 21:01
MemberASysSolvers3-Apr-08 21:01 
QuestionMissing Code and Examples? Pin
Member 361497712-Dec-07 10:44
MemberMember 361497712-Dec-07 10:44 
AnswerRe: Missing Code and Examples? Pin
StormySpike21-Dec-07 3:21
MemberStormySpike21-Dec-07 3:21 
Questionkey combination Pin
simply_joe16-Sep-07 18:47
Membersimply_joe16-Sep-07 18:47 
AnswerRe: key combination Pin
UB90913-Jan-08 3:24
MemberUB90913-Jan-08 3:24 
QuestionRe: key combination Pin
Dregor27-Apr-08 10:37
MemberDregor27-Apr-08 10:37 

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.