65.9K
CodeProject 正在变化。 阅读更多。
Home

WinCE 中的键盘挂钩

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.61/5 (7投票s)

2005年11月3日

CPOL

1分钟阅读

viewsIcon

99805

downloadIcon

945

一篇关于在 WinCE 中使用键盘钩子的文章。

引言

本文档展示了如何在 WinCE 中使用键盘钩子。

背景

我遇到一个问题,需要为现有的基于对话框的应用程序**重新映射**手持设备上的某些特殊键。我知道的唯一可以在 WinCE 中优雅地完成此操作的解决方案是使用钩子。但是 MSDN 声明钩子 API 在 WinCE 中不受支持。但我发现它们存在于 coredll.lib 中。所以我考虑手动加载这些 API 并使用它们。最初我确实在使用这个过程中遇到了一些问题,但查看 VC++ 中的 winuser.h,让这项工作变得容易多了。在 Google 上搜索也帮了我一些忙,但我现在不记得网址了。向那些我没有给予信誉的人表示歉意。

使用代码

您只需要使用两个文件 winceKBhook.cppwinceKBhook.h。代码已充分注释,以便于理解。您可以在 exe 或 DLL 中使用这些文件。

使用钩子的机制是安装它。这使用 winceKBhook.cpp 中的函数完成,即 ActivateKBHook()。此函数加载必要的钩子 API 并安装 KB 钩子。有必要传递要钩子的应用程序的句柄以及用户定义的低级别 KB 程序。所有键盘事件都将发送到此过程。然后,您的代码可以以您想要的方式管理这些事件。以下示例只是重新映射按键。完成使用钩子后,使用 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();
© . All rights reserved.