Click here to Skip to main content
Licence CPOL
First Posted 30 May 2007
Views 230,344
Downloads 10,398
Bookmarked 111 times

A Simple C# Global Low Level Keyboard Hook

By | 30 May 2007 | Article
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...

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

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

[DllImport("user32.dll")]
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.

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)

About the Author

StormySpike

Software Developer

United States United States

Member

I currently work as a Software Engineer for a company in North Carolina, mainly working with C#.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionkey combination Pinmemberjosephlawrencecarpio17:47 16 Sep '07  
AnswerRe: key combination PinmemberUB9092:24 13 Jan '08  
QuestionRe: key combination PinmemberDregor9:37 27 Apr '08  
GeneralRe: key combination PinmemberMaxWalter11:23 20 Aug '08  
QuestionRe: key combination PinmemberDiamonddrake17:21 29 Dec '08  
GeneralThanks PinmemberNasenbaaer6:42 24 Jul '07  
GeneralCallbackOnCollectedDelegate Pinmemberdubious_mauvo7:18 21 Jul '07  
When I tried using this class in VS2005 I got the following message:
 
Managed Debugging Assistant 'CallbackOnCollectedDelegate' has detected a problem in 'C:\AEQ\EyeQ\EyeQ 1.6.1 Net 2\Eyeq\bin\Debug\EyeQ.vshost.exe'.
Additional Information: A callback was made on a garbage collected delegate of type 'EyeQ!EyeQ.Common.GlobalKeyboardHook+keyboardHookProc::Invoke'. This may cause application crashes, corruption and data loss. When passing delegates to unmanaged code, they must be kept alive by the managed application until it is guaranteed that they will never be called.
 
The solution I found was to declare an instance of the keyboardHookProc, which is then initialised in the constructor and is passed in the SetWindowsHookEx in place of hookProc.
QuestionRe: CallbackOnCollectedDelegate PinmemberLenFH11:28 13 Aug '07  
AnswerRe: CallbackOnCollectedDelegate PinPopularmemberdubious_mauvo2:07 15 Aug '07  
GeneralRe: CallbackOnCollectedDelegate Pinmemberkirillkornyakov22:50 2 Feb '10  
GeneralRe: CallbackOnCollectedDelegate Pinmemberhaitham hamed housin7:41 30 Mar '10  
GeneralRe: CallbackOnCollectedDelegate Pinmemberjrbosch22:52 2 Jan '11  
GeneralRe: CallbackOnCollectedDelegate Pinmemberrafinhacsm1:01 27 Dec '11  
GeneralRe: CallbackOnCollectedDelegate Pinmemberdullan15:46 27 Feb '12  
AnswerRe: CallbackOnCollectedDelegate Pinmemberjeanlucvalestin1:14 16 Nov '08  
GeneralRe: CallbackOnCollectedDelegate Pinmemberjeanlucvalestin1:16 16 Nov '08  
GeneralRe: CallbackOnCollectedDelegate PinmemberOzan Müyesseroğlu14:31 29 Dec '11  
GeneralSet hooked key by variable Pinmember~Rob5:03 9 Jul '07  
AnswerRe: Set hooked key by variable PinmemberStormySpike16:36 10 Jul '07  
GeneralRe: Set hooked key by variable Pinmemberlancesh4:55 3 Apr '08  
GeneralRe: Set hooked key by variable PinmemberStormySpike5:00 16 Apr '08  
GeneralWindows Vista Pinmembernone42:29 7 Jul '07  
GeneralRe: Windows Vista Pinmembernone42:32 7 Jul '07  
GeneralHi from Guayquil-Ecuador PinmemberOneSoftware20:27 30 May '07  
AnswerRe: Hi from Guayquil-Ecuador PinmemberStormySpike2:39 31 May '07  

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.

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