Thursday, March 6, 2008

Windows CE Keyboard Hook

Windows CE Keyboard Hook


http://weibeltech.com/?p=110

A teammate needed to write a Windows CE Keyboard Hook. So I gave them a hand, after doing a little digging I came across this posting. Many thanks to Prathamesh S Kulkarni for this post.

http://www.codeproject.com/ce/wincekbhook.asp?print=true
I duplicated the core of this sample code below so I don’t loose it in the future. Check out Prathamesh’s code for commented code. To make this work call activate() at the beginning of your app.
if (!activate(hInst, hook)) {
return FALSE;
}
And deactivate() at the end.
deactivate();
Then fill in the hook() with some interesting logic.

#include 
#include
#include

#define WH_KEYBOARD_LL 20

typedef LRESULT (CALLBACK* HOOKPROC)(int code, WPARAM wParam, LPARAM lParam);
typedef HHOOK (WINAPI *_SetWindowsHookExW)(int, HOOKPROC, HINSTANCE, DWORD);
typedef LRESULT (WINAPI *_CallNextHookEx)(HHOOK, int, WPARAM, LPARAM);
typedef LRESULT (WINAPI *_UnhookWindowsHookEx)(HHOOK);

typedef struct {
DWORD vkCode;
DWORD scanCode;
DWORD flags;
DWORD time;
ULONG_PTR dwExtraInfo;
} KBDLLHOOKSTRUCT, *PKBDLLHOOKSTRUCT;

static _SetWindowsHookExW SetWindowsHookEx;
static _UnhookWindowsHookEx UnhookWindowsHookEx;
static _CallNextHookEx CallNextHookEx;

HINSTANCE gHook = NULL;
HHOOK gInst = NULL;

BOOL activate(HINSTANCE, HOOKPROC);
BOOL deactivate();
LRESULT CALLBACK hook(int nCode, WPARAM wParam, LPARAM lParam);

//
// activate() -
//
BOOL
activate(HINSTANCE hInst, HOOKPROC hProc)
{
SetWindowsHookEx = NULL;
CallNextHookEx = NULL;
UnhookWindowsHookEx = NULL;

gHook = LoadLibrary(_T("coredll.dll"));
if(gHook == NULL) {
return(false);
} else {

SetWindowsHookEx = (_SetWindowsHookExW)GetProcAddress(
gHook, _T("SetWindowsHookExW"));
if(SetWindowsHookEx == NULL) {
return(false);
} else {
gInst = SetWindowsHookEx(WH_KEYBOARD_LL, hProc, hInst, 0);
if(gInst == NULL) {
return false;
}
}

CallNextHookEx = (_CallNextHookEx)GetProcAddress(
gHook, _T("CallNextHookEx"));
if(CallNextHookEx == NULL) {
return false;
}

UnhookWindowsHookEx = (_UnhookWindowsHookEx)GetProcAddress(
gHook, _T("UnhookWindowsHookEx"));
if(UnhookWindowsHookEx == NULL) {
return(false);
}
}
return(true);
}


//
// deactivate() -
//
BOOL
deactivate()
{
if(gInst != NULL) {
UnhookWindowsHookEx(gInst);
gInst = NULL;
}
if(gHook != NULL) {
FreeLibrary(gHook);
gHook = NULL;
}
return(true);
}

//
// hook() -
//
LRESULT CALLBACK
hook(int nCode, WPARAM wParam, LPARAM lParam)
{
// Do something interesting here
return CallNextHookEx(gInst, nCode, wParam, lParam);
}

No comments: