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

在 WinCE 中使用键盘钩子

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.57/5 (13投票s)

2005 年 11 月 1 日

CPOL

1分钟阅读

viewsIcon

169170

downloadIcon

1350

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

引言

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

背景

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

使用代码

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

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