Click here to Skip to main content
15,890,123 members
Articles / Mobile Apps

Using keyboard hooks in WinCE

Rate me:
Please Sign up or sign in to vote.
4.57/5 (14 votes)
1 Nov 2005CPOL1 min read 163.6K   1.3K   39   32
The article shows how to use keyboard hooks in WinCE.

Introduction

The article shows how to use keyboard hooks in WinCE.

Background

I came across a problem where I had to remap certain special keys on my handheld for an existing dialog based application. The only solution I knew that would gracefully do this in WinCE was hooks. But MSDN states that hook APIs aren't supported in WinCE. But I found that they were present in coredll.lib. So, I thought of manually loading these APIs and using them. Initially, I did have some problems doing this, but a look into winuser.h in VC++, made the job a lot easier. Googling also helped me to some extent, but I don't remember the URLs now, my apologies to those whom I haven't given the credit.

Using the code

You just have to use two files winceKBhook.cpp and winceKBhook.h. The code has been commented thoroughly for easy understanding. You can use these files in either an EXE or a DLL.

The mechanism of using a hook would be to install it. This is done using the function ActivateKBHook() in winceKBhook.cpp. This function loads the necessary hook APIs and installs the keyboard hook. It is necessary to pass the handle of the application to be hooked and a low level keyboard procedure, which has to be defined by the user. All the keyboard events come to this procedure. Your code can then manage these events the way you want. The example shown below just remaps the keys. After you are done with using the hook you can unload it using DeActivateKBHook().

//Install the KB hook by passing the 
//handle of the application to be hooked 
//and the address of the KB procedure 
//which will handle all the KB events
if(!ActivateKBHook(hInstance, LLKeyboardHookCallbackFunction))
{
    MessageBox(GetActiveWindow(), 
        TEXT("Couldn't intall hook...Terminating"), 
        TEXT("Warning"), NULL);
    exit(1);
}

//LLKeyboardHookCallbackFunction is the funtion whose 
//address we passed to the system while installing the hook.
//so all the KB events will bring the control to this procedure.
//Here we want that when the user presse left or 
//right key it should be interpreted as an UP key
//so now you can allow the user to configure the 
//key boards the way he/she wants it
LRESULT CALLBACK LLKeyboardHookCallbackFunction(
                  int nCode, WPARAM wParam, LPARAM lParam) 
{
    if(((((KBDLLHOOKSTRUCT*)lParam)->vkCode) == VK_LEFT) || 
           ((((KBDLLHOOKSTRUCT*)lParam)->vkCode) == VK_RIGHT))
    {
        //Generate the keyboard press event of the mapped key
        keybd_event(VK_UP, 0, 0, 0); 

        //release the mapped key
        keybd_event(VK_UP, 0, KEYEVENTF_KEYUP, 0); 
    }

    //let default processing take place
    return CallNextHookEx(g_hInstalledLLKBDhook, nCode, 
                                              wParam, lParam);
}

//we are done with the hook. now uninstall it.
DeactivateKBHook();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


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

Comments and Discussions

 
QuestionHow to create DLL from this for usage with C# Pin
Member 125398842-Jun-16 21:25
Member 125398842-Jun-16 21:25 
QuestionIt works on WINCE6.0, but the keycode always 0? Pin
selongs10-Sep-09 4:40
selongs10-Sep-09 4:40 
Generalis it work on windows mobile 5 or above Pin
zeroonea25-Jun-09 20:15
zeroonea25-Jun-09 20:15 
GeneralStill a great article Pin
hjgode15-May-09 19:13
hjgode15-May-09 19:13 
QuestionIndependant hooks? Pin
JDBP17-Mar-09 5:26
JDBP17-Mar-09 5:26 
AnswerRe: Independant hooks? Pin
hjgode15-May-09 19:17
hjgode15-May-09 19:17 
QuestionA Global Hook? Pin
Angel Kafazov14-Aug-08 4:55
Angel Kafazov14-Aug-08 4:55 
GeneralApplications does not follow Emulator keyboard. Pin
Shashi.Shinde25-Apr-08 0:44
Shashi.Shinde25-Apr-08 0:44 
GeneralWinCE hooks using SetWinEventHook Pin
Shashi.Shinde23-Apr-08 19:30
Shashi.Shinde23-Apr-08 19:30 
Hello Sir,

I had gone through your above article. It is very informative and helpful. Thank you for posting such article.

Well,
I have to code a hook in WinCE using SetWinEventHook.

I had tried your explained method as above, but not able to create hook. I am getting following errors -
Generating Code...
Compiling resources...
Linking...
MainFrm.obj : error LNK2019: unresolved external symbol "struct HWINEVENTHOOK__ * __cdecl SetWinEventHook(unsigned long,unsigned long,struct HINSTANCE__ *,void (__cdecl*)(struct HWINEVENTHOOK__ *,unsigned long,struct HWND__ *,long,long,unsigned long,unsigned long),unsigned long,unsigned long,unsigned long)" (?SetWinEventHook@@YAPAUHWINEVENTHOOK__@@KKPAUHINSTANCE__@@P6AXPAU1@KPAUHWND__@@JJKK@ZKKK@Z) referenced in function "protected: int __cdecl CMainFrame::OnCreate(struct tagCREATESTRUCTW *)" (?OnCreate@CMainFrame@@IAAHPAUtagCREATESTRUCTW@@@Z)
Windows Mobile 5.0 Pocket PC SDK (ARMV4I)\Release/ScureApp.exe : fatal error LNK1120: 1 unresolved externals

Please have a quick look on my code as follows -
my MainFrm :: OnCreate() contains

g_hHkApiDLL = LoadLibrary(_T("user32.dll"));
g_hHkApiDLLBox = LoadLibrary(_T("coredll.dll"));

if((g_hHkApiDLLBox && g_hHkApiDLL) == NULL)
{
AfxMessageBox(_T("Error to load coredll.dll"));
//something is awfully wrong
//the dll has to be present
return false;
}
else
{
//load the SetWindowsHookEx API call
//the SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
//You would install a hook procedure to monitor the system for certain types of events.
//here we use use the hook to monitor kyeboard events
LPTSTR pSetWinEventHook;
pSetWinEventHook = (LPTSTR)GetProcAddress(g_hHkApiDLLBox, _T("SetWinEventHook"));
if(pSetWinEventHook == NULL)
{
AfxMessageBox(_T("Error to install hook procedure"));
//this means that MS has really stopped supporting this API in WinCE
return false;
}
else
{
//SetWindowRetProcHook (TRUE);
// hEvtHook = SetWinEventHook (EVENT_MIN, EVENT_MAX,
hEvtHook = SetWinEventHook (EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND,
NULL, ForegroundProc, 0, 0,
WINEVENT_OUTOFCONTEXT);
}
}

My ForgroundProc as follows -

VOID CALLBACK ForegroundProc( HWINEVENTHOOK hWinEventHook, DWORD event, HWND hwnd,LONG idObject, LONG idChild, DWORD dwEventThread, DWORD dwmsEventTime )
{
AfxMessageBox(_T("Inside ForegroundProc"));
TCHAR buf[MAX_PATH];

HWND hWndForeGroundWin = GetForegroundWindow();
if (GetClassName(hWndForeGroundWin, buf, MAX_PATH))
{
if (!_tcsicmp (buf, TEXT("IEFRAME")) ||
_tcsstr (buf, TEXT("Internet Explorer")) ||
!_tcsicmp (buf, TEXT("MozillaUIWindowClass")))
{
AfxMessageBox(TEXT("Found Internet Explorer_Server"));
}
}
}

Also we have declared in WinceKBkook.h file -
HINSTANCE g_hHookApiDLL = NULL; //handle to coredll.dll, where all the hook related APIs are present
HHOOK g_hInstalledLLKBDhook = NULL; //g_hInstalledLLKBDhook represents handle to the installed KB hook
#define EVENT_SYSTEM_FOREGROUND 0x0003
#define WINEVENT_OUTOFCONTEXT 0x0000 // Events are ASYNC


typedef VOID (CALLBACK* WINEVENTPROC)(
HWINEVENTHOOK hWinEventHook,
DWORD event,
HWND hwnd,
LONG idObject,
LONG idChild,
DWORD idEventThread,
DWORD dwmsEventTime);

//typedef HWINEVENTHOOK (WINAPI *SetWinEventHook)(DWORD, DWORD, HMODULE, WINEVENTPROC, DWORD, DWORD, DWORD);


//extern "C"
WINUSERAPI
HWINEVENTHOOK
WINAPI
SetWinEventHook(
__in DWORD eventMin,
__in DWORD eventMax,
__in_opt HMODULE hmodWinEventProc,
__in WINEVENTPROC pfnWinEventProc,
__in DWORD idProcess,
__in DWORD idThread,
__in DWORD dwFlags);

Now request you, please look into the code, and suggest me where I am getting wrong.

Thanks.

Regards,

Shashikant
Questionproblem in porting wince to smdk 2410 board. Pin
amiya das30-Mar-08 21:47
amiya das30-Mar-08 21:47 
GeneralYou are Rock Pin
Dr.Luiji13-Mar-08 6:58
professionalDr.Luiji13-Mar-08 6:58 
Questionwhy SetWindowsHookEx always return NULL Pin
xingtian71313-May-07 21:41
xingtian71313-May-07 21:41 
Questionhi...i Need Mouse Hook for WinCE Pin
Asia_Mouse1-Aug-06 23:26
Asia_Mouse1-Aug-06 23:26 
QuestionOther hook message? Pin
Chang Yin-Tse18-Jun-06 20:54
Chang Yin-Tse18-Jun-06 20:54 
AnswerRe: Other hook message? Pin
Prathamesh S Kulkarni20-Jun-06 19:47
Prathamesh S Kulkarni20-Jun-06 19:47 
AnswerRe: Other hook message? Pin
Chang Yin-Tse27-Jun-06 16:54
Chang Yin-Tse27-Jun-06 16:54 
QuestionRe: Other hook message? Pin
ShishirAgarwal26-Jul-06 19:38
ShishirAgarwal26-Jul-06 19:38 
AnswerRe: Other hook message? Pin
Chang Yin-Tse10-Aug-06 16:44
Chang Yin-Tse10-Aug-06 16:44 
GeneralRe: Other hook message? Pin
Rahul P. Shukla2-Jul-07 1:39
Rahul P. Shukla2-Jul-07 1:39 
GeneralGetting compilation error [modified] Pin
santu22-May-06 20:38
santu22-May-06 20:38 
AnswerRe: Getting compilation error [modified] Pin
Prathamesh S Kulkarni24-May-06 15:50
Prathamesh S Kulkarni24-May-06 15:50 
GeneralDisable Contacts - Messages Buttons Pin
Vittorio Iezzoni7-May-06 23:04
Vittorio Iezzoni7-May-06 23:04 
GeneralAccess Violation Pin
Vittorio Iezzoni20-Feb-06 23:45
Vittorio Iezzoni20-Feb-06 23:45 
AnswerRe: Access Violation Pin
Prathamesh S Kulkarni21-Feb-06 7:32
Prathamesh S Kulkarni21-Feb-06 7:32 
GeneralRe: Access Violation Pin
Vittorio Iezzoni21-Feb-06 20:51
Vittorio Iezzoni21-Feb-06 20:51 

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.