Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C++
Article

KeyBoard Hooks

Rate me:
Please Sign up or sign in to vote.
4.76/5 (40 votes)
23 Jul 20012 min read 846.7K   20.4K   163   141
This example shows how to write global hooks .This program captures all the Keyboard events and save the keys to a text file.

Introduction

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)) 
        {
            f1=fopen("c:\\report.txt","a+");
            if (wParam==VK_RETURN)
            {
                ch='\n';
                fwrite(&ch,1,1,f1);
            }
            else
            {
                   BYTE ks[256];
                GetKeyboardState(ks);

                WORD w;
                UINT scan=0;
                ToAscii(wParam,scan,ks,&w,0);
                ch = char(w); 
                fwrite(&ch,1,1,f1);
            }
        fclose(f1);
        }
    }

    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()
{
    f1=fopen("c:\\report.txt","w");
    fclose(f1);
    hkb=SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)KeyboardProc,hins,0);

    return TRUE;
}

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerRe: SetWindowsHookEx:WINDOWS 2000 Pin
J51219822-Mar-06 18:37
J51219822-Mar-06 18:37 
Questiontrap ALT+number Pin
Haridasi3-Sep-05 8:45
Haridasi3-Sep-05 8:45 
GeneralMonitorize mouse global events in WINDOWS-CE; Pin
XBSANTOS3-May-05 21:34
XBSANTOS3-May-05 21:34 
GeneralRe: Monitorize mouse global events in WINDOWS-CE; Pin
sakkaravarthy22-Nov-06 20:01
sakkaravarthy22-Nov-06 20:01 
GeneralRe: Monitorize mouse global events in WINDOWS-CE; Pin
Paul Heil27-Oct-10 4:33
Paul Heil27-Oct-10 4:33 
GeneralGlobal Kyboard Hooks Pin
iontodirel1-Apr-05 22:08
iontodirel1-Apr-05 22:08 
GeneralWH_KEYBOARD_LL not capture all key events Pin
XBSANTOS28-Mar-05 8:34
XBSANTOS28-Mar-05 8:34 
GeneralWH_JOURNALRECORD Windows CE Global Hook is blocked! Pin
XBSANTOS24-Mar-05 6:33
XBSANTOS24-Mar-05 6:33 
WH_JOURNALRECORD Windows CE Global Hook is blocked!

Hello,

how are you?

You can help me? I'm working in a WINDOWS CE 3.0 project with Microsoft Visual Studio C++ Embedded
3.0, and I'm using a WH_JOURNALRECORD Windows CE global hook.

I create the hook:

m_hHkJournalRec = m_pfSetWindowsJournalHook(WH_JOURNALRECORD, JournalRecordProc, aInstance, 0);

m_pfSetWindowsJournalHook is a pointer to the QASetWindowsJournalHook function, that's in the
coredll.dll library.

I have a JournalRecordProc process, and finally I want to delete the global hook:

m_pfUnhookWindowsJournalHook(m_hHkJournalRec)

where m_pfUnhookWindowsJournalHook is a pointer to the QAUnhookWindowsJournalHook function, that's in
the coredll.dll library.

And my problem, is that this function returns false, instead of true, and that wants to say that
the global hook isn't deleted correctly, and the system resources are not free. In addition, when
my application finishes in the Pocket PC, the PDA becomes blocked, and it doesn't detect any other
keyboard or mouse event, and I have to do a software reset.

There is a function, called GetLastError(), that gives you the last error that happens in the
system, but this function returns 0, that wants to say, "all is correct". Someone can help me, and
knows how delete this global hook correctly?

HINSTANCE aInstance = GetModuleHandle(NULL); --> aInstance makes reference to real module, not
to a dll, it's not necessary! (it can be also an EXE file);

What do you think about it?

Thanks,

Sincerely,

javitobcn (barcelona SPAIN).


hola
GeneralUnHook in VB Pin
Member 178485317-Mar-05 2:42
Member 178485317-Mar-05 2:42 
GeneralGlobal Hooks for Pocket PC Pin
XBSANTOS11-Mar-05 6:11
XBSANTOS11-Mar-05 6:11 
GeneralRe: Global Hooks for Pocket PC Pin
mavl42197-Sep-05 20:51
mavl42197-Sep-05 20:51 
Generalunhandled exception Pin
Member 17848537-Mar-05 4:41
Member 17848537-Mar-05 4:41 
GeneralRe: unhandled exception Pin
Anonymous10-Mar-05 1:47
Anonymous10-Mar-05 1:47 
GeneralRe: unhandled exception Pin
sakkaravarthy22-Nov-06 19:51
sakkaravarthy22-Nov-06 19:51 
Generaldifferentiate b/n virtual keys and Real Keyboard Event Pin
mahesh kumar s12-Oct-04 21:00
mahesh kumar s12-Oct-04 21:00 
QuestionHow to change a key Pin
Member 3120817-Oct-04 5:39
Member 3120817-Oct-04 5:39 
GeneralKeyboard Hook Pin
Member 111258427-Sep-04 0:52
Member 111258427-Sep-04 0:52 
GeneralRe: Keyboard Hook Pin
sakenu1627-Oct-06 4:48
sakenu1627-Oct-06 4:48 
GeneralI want to get which key that user press Pin
tola_ch20043-Sep-04 16:33
tola_ch20043-Sep-04 16:33 
QuestionHow to get Title of Window Pin
navinkaus1-Aug-04 1:49
navinkaus1-Aug-04 1:49 
AnswerRe: How to get Title of Window Pin
asdklasjdlaskj6-Feb-07 7:56
asdklasjdlaskj6-Feb-07 7:56 
GeneralI want help Pin
ibikhan17-Jul-04 1:03
ibikhan17-Jul-04 1:03 
GeneralRe: I want help Pin
sakkaravarthy22-Nov-06 19:54
sakkaravarthy22-Nov-06 19:54 
Generalaccess datawindow Pin
tang1000713-Nov-03 21:02
tang1000713-Nov-03 21:02 
GeneralHookApi SourceCode Pin
xiamy8-Nov-03 6:32
xiamy8-Nov-03 6:32 

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.