Click here to Skip to main content
15,861,172 members
Articles / Programming Languages / C#
Article

A Simple C# Global Low Level Keyboard Hook

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

C#
using Utilities;

... to the top of the file you are going to use it in. Next add an instance of globalKeyboardHook to your class:

C#
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:

C#
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:

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

C#
[DllImport("user32.dll")]
static extern IntPtr SetWindowsHookEx
    (int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);

The parameters were worked out to be:

C#
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)


Written By
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

 
QuestionPossible usage as a windows service Pin
Quirk198726-Dec-23 10:11
Quirk198726-Dec-23 10:11 
AnswerRe: Possible usage as a windows service Pin
OriginalGriff26-Dec-23 10:15
mveOriginalGriff26-Dec-23 10:15 
GeneralRe: Possible usage as a windows service Pin
Quirk198728-Dec-23 0:32
Quirk198728-Dec-23 0:32 
QuestionCrash App on 280± KEYDOWN Pin
Rooctor2-Jun-22 21:52
Rooctor2-Jun-22 21:52 
AnswerRe: Crash App on 280± KEYDOWN Pin
Rooctor3-Jun-22 2:27
Rooctor3-Jun-22 2:27 
Praisegreat code Pin
Member 149076167-Apr-21 1:05
Member 149076167-Apr-21 1:05 
BugIs this still supposed to work with windows 10? Pin
Guieha13-Feb-20 8:28
Guieha13-Feb-20 8:28 
GeneralRe: Is this still supposed to work with windows 10? Pin
Flatty8828-Oct-20 8:57
Flatty8828-Oct-20 8:57 
QuestionIn my case I need that by pressing the A and B keys I can write them where the focus is, which can change in the code, please help Pin
Member 1472008221-Jan-20 3:27
Member 1472008221-Jan-20 3:27 
QuestionEn mi caso necesito que al presionar las teclas A y B las pueda escribir en donde esta el foco, que tendría que cambiar en el codigo, ayuda por favor Pin
Member 1472008221-Jan-20 3:30
Member 1472008221-Jan-20 3:30 
QuestionTHANK YOU! Pin
Rocky Villalobos Bitos Jr.7-Jun-18 15:35
Rocky Villalobos Bitos Jr.7-Jun-18 15:35 
BugWill not pass modifiers into the KeyEventHandler method Pin
Joshua Parnell6-Jan-17 0:34
Joshua Parnell6-Jan-17 0:34 
AnswerRe: Will not pass modifiers into the KeyEventHandler method Pin
Joshua Parnell6-Jan-17 6:47
Joshua Parnell6-Jan-17 6:47 
AnswerRe: Will not pass modifiers into the KeyEventHandler method Pin
SkipperTr19-Jan-23 6:41
SkipperTr19-Jan-23 6:41 
QuestionCraching if key was long pressed and more Pin
Matt Grunig8-Nov-16 16:06
Matt Grunig8-Nov-16 16:06 
AnswerRe: Craching if key was long pressed and more Pin
Rocky Villalobos Bitos Jr.7-Jun-18 19:00
Rocky Villalobos Bitos Jr.7-Jun-18 19:00 
Questionhow do i detect if only one of the keys Pin
Member 1255194217-Jun-16 5:51
Member 1255194217-Jun-16 5:51 
AnswerRe: how do i detect if only one of the keys Pin
Crazy Gaming19-May-22 8:08
Crazy Gaming19-May-22 8:08 
Questiondisble ctrl+alt+del Pin
Member 123719125-Mar-16 10:27
Member 123719125-Mar-16 10:27 
AnswerRe: disble ctrl+alt+del Pin
Member 1224827127-Apr-16 3:45
Member 1224827127-Apr-16 3:45 
QuestionEvents fire only when app window on focus (only none letters fires when not focused) Pin
_Ecke_27-Apr-15 8:59
_Ecke_27-Apr-15 8:59 
GeneralVery Good job bro Pin
HelloHelloRain26-Nov-14 14:39
HelloHelloRain26-Nov-14 14:39 
QuestionBeginner Problem Pin
Member 1108671516-Sep-14 13:57
Member 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
chocolade16-Sep-14 10:40 
GeneralMy vote of 5 Pin
Member 1035479628-Jul-14 22:24
Member 1035479628-Jul-14 22:24 

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.