Click here to Skip to main content
11,411,494 members (63,873 online)
Click here to Skip to main content

KeyBoard Hooks

, 23 Jul 2001
Rate this:
Please Sign up or sign in to vote.
This example shows how to write global hooks .This program captures all the Keyboard events and save the keys to a text file.
<!-- Download Links --> <!-- Main HTML starts here -->


Hooks are one of the most powerful features of Windows. We can hooks to trp all the events in the Windows environment. This example shows how to trap keyboard events and save the keys to a text file.

In the Microsoft® Windows™ operating system, a hook is a mechanism by which a function can intercept events (messages, mouse actions, keystrokes) before they reach an application. The function can act on events and, in some cases, modify or discard them. Functions that receive events are called filter functions and are classified according to the type of event they intercept. For example, a filter function might want to receive all keyboard or mouse events. For Windows to call a filter function, the filter function must be installed — that is, attached to a Windows hook (for example, to a keyboard hook). Attaching one or more filter functions to a hook is known as setting a hook. If a hook has more than one filter function attached, Windows maintains a chain of filter functions. The most recently installed function is at the beginning of the chain, and the least recently installed function is at the end.

When a hook has one or more filter functions attached and an event occurs that triggers the hook, Windows calls the first filter function in the filter function chain. This action is known as calling the hook. For example, if a filter function is attached to the Computer Based Training (CBT) hook and an event that triggers the hook occurs (for example, a window is about to be created), Windows calls the CBT hook by calling the first function in the filter function chain.

To maintain and access filter functions, applications use the SetWindowsHookEx and the UnhookWindowsHookEx functions.

An Example

The CALLBACK function in my example is given below..

LRESULT __declspec(dllexport)__stdcall  CALLBACK KeyboardProc(int nCode,WPARAM wParam, 
                            LPARAM lParam)
    char ch;            
    if (((DWORD)lParam & 0x40000000) &&(HC_ACTION==nCode))
        if ((wParam==VK_SPACE)||(wParam==VK_RETURN)||(wParam>=0x2f ) &&(wParam<=0x100)) 
            if (wParam==VK_RETURN)
                   BYTE ks[256];

                WORD w;
                UINT scan=0;
                ch = char(w); 

    LRESULT RetVal = CallNextHookEx( hkb, nCode, wParam, lParam );
    return  RetVal;

The installhook function that is installing the hook function in my example is given below.

BOOL __declspec(dllexport)__stdcall installhook()

    return TRUE;


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

H. Joseph

United States United States
No Biography provided

Comments and Discussions

Questionwhat is the first condition for? PinmemberJayapal Chandran3-Aug-13 6:18 
AnswerRe: what is the first condition for? PinprofessionalRajesh R Subramanian23-Oct-14 20:55 
QuestionHow to set Key combination (like SHIFT+F9 etc.) as hook PinmemberMember 783682923-Aug-11 20:57 
QuestionExample in Assembly Language PinmemberMember 810561222-Jul-11 10:38 
GeneralThanks very much Pinmemberachui198031-Mar-11 17:45 
GeneralHook not working fine if Keyboard Language is Change Pinmembereg_Anubhava1-Feb-11 2:30 
Generalapplication crash when click on iexplore 7 Pinmembercjsc20-Mar-10 11:08 
AnswerRe: application crash when click on iexplore 7 PinmemberBMaguire24-May-11 9:02 
GeneralWhich hook is good for trapping Windows Key + some other Key as shortcut PinmemberArif Saiyed27-Jan-10 3:29 
QuestionDiscard Event PinmemberErin McCarty9-Jun-09 16:51 
QuestionMessageBox within Hook-Function Pinmembernoxmortis12-Aug-08 2:17 
GeneralPlease help me Pinmembersomnuc8-Aug-08 18:05 
QuestionUnhandled Exception? PinmemberAdrian Parker15-Feb-08 8:56 
AnswerRe: Unhandled Exception? PinmemberAdrian Parker15-Feb-08 9:11 
Questiontyping assistance (hook) Pinmembernguyenkim25-Oct-07 18:09 
Questionare the dll global variables local to each process? Pinmemberfoxx 133725-Jul-07 8:59 

I wanted to make a program that hides applications (Enemy Territory - WM_KEY..., Quake 4 - DirectInput) which don't accept alt-tab.
When I press X, first Quake 4 is to disappear, then if I press X again, it should pop out (X will be changed to something configurable through the loader app).
My approach is as follows:

#pragma data_seg (".shared")
static bool keys[256];
static const TCHAR CLASS_ET[] = TEXT("Enemy Territory");
static const TCHAR CLASS_Q4[] = TEXT("Quake4");
static int cmdShow = SW_HIDE; // I first hide Quake, then i show it, etc
#pragma data_seg ()

	KeyboardProc @1
	InstallHook  @2
	ReleaseHook  @3
	.shared SHARED
in the .def file.

I've noticed that if i don't do the trick with the shared data segment, the DllMain of my DLL will be called with DLL_PROCESS_ATTACH for each new application, with a different cmdShow state-variable. For example, if I load my DLL, then I go into Quake 4 and press X, Quake 4 will receive a ShowWindow(SW_HIDE), then if I get into Total Commander and press X, Quake 4 will receive
ShowWindow(SW_HIDE). I think that's because a different version of my DLL file exists for the Windows Desktop and a different one for Total Commander (despite LoadLibrary is only called from within my loader application).

Am I correct that my DLL is being injected into all the applications, with the DLL local variables instantiated each time?

Here's the DLL code for reference:
#include <windows.h>
#include "KBD.h"
#include <stdio.h>
static HHOOK hkb;
static HINSTANCE hins;
static HWND hwnd;
#pragma data_seg (".shared")
static bool keys[256];
static const TCHAR CLASS_ET[] = TEXT("Enemy Territory");
static const TCHAR CLASS_Q4[] = TEXT("Quake4");
static int cmdShow = SW_HIDE;
#pragma data_seg ()
int WINAPI DllMain(HINSTANCE hInstance, DWORD fdwReason, PVOID pvReserved)
	hkb = NULL;
	hins = hInstance;
	return TRUE;
extern "C" LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
	FILE *fp = fopen("f:\\src\\C\\SDK\\testkb\\Debug\\log.log", "a+");
	if (HC_ACTION == nCode) {
		if (0 == (static_cast<DWORD>(lParam) & (1 << 31)) && 0 == (static_cast<DWORD>(lParam) & (1 << 30))) {
			keys[wParam] = true;
			fprintf(fp, "pressed %c\n", wParam);
			if (keys['X']) {
				HWND wnd = FindWindow(CLASS_ET, NULL);
				if (NULL == wnd) wnd = FindWindow(CLASS_Q4, NULL);
				if (NULL != wnd) {
					fprintf(fp, "\tShowWindow(%s)\n", SW_HIDE == cmdShow ? "SW_HIDE" : "SW_SHOW");
					ShowWindow(wnd, cmdShow);
					cmdShow = ((SW_HIDE == cmdShow) ? SW_SHOW : SW_HIDE);
		else if (static_cast<DWORD>(lParam) & (1 << 31)) {
			keys[wParam] = false;
			fprintf(fp, "released %c\n", wParam);
	LRESULT RetVal = CallNextHookEx(hkb, nCode, wParam, lParam);
	return RetVal;
extern "C" void InstallHook(HWND hWnd)
	hwnd = hWnd;
	hkb = SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyboardProc, hins, 0);
	if (NULL == hkb) {
		TCHAR msg[256];
		wsprintf(msg, TEXT("error code: %d"), GetLastError());
		MessageBox(NULL, msg, TEXT("error"), MB_ICONERROR);
extern "C" void ReleaseHook()
	if (hkb != NULL)

AnswerRe: are the dll global variables local to each process? PinmemberSunny127023-Feb-11 7:35 
QuestionKeyboard Hook working partly PinmemberJayapal Chandran17-Jun-07 2:39 
GeneralRe: Keyboard Hook working partly Pinmemberfoxx 133725-Jul-07 9:02 
GeneralThe low level approach PinmemberEl_Khlifi_Abdellatif5-May-07 13:28 
QuestionProblem after lock Workstation need Help Pinmemberskywalker327-Mar-07 23:34 
GeneralWindow movement restriction PinmemberAKG20-Feb-07 23:00 
GeneralRe: Window movement restriction Pinmemberbitslayer14-Mar-07 11:05 
Generalhelp Pinmembermailtochandra2000@yahoo.com20-Feb-07 19:54 
Generalhelp me Pinmembermailtochandra2000@yahoo.com15-Feb-07 0:04 

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.5 | Last Updated 24 Jul 2001
Article Copyright 2001 by H. Joseph
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid