简体   繁体   English

Win32 C ++低级键盘挂钩导致异常行为

[英]Win32 C++ Low Level Keyboard Hook causing strange behavior

I am having a problem trying to use a keyboard hook. 我在尝试使用键盘挂钩时遇到问题。 What I am trying to do (and does) is from any window/ focus, I can hit a key that runs a function (that moves the mouse and clicks.) 我想做的(或做的)是从任何窗口/焦点开始的,我可以敲击一个运行功能的键(移动鼠标并单击)。

It works just fine from the front, but as soon as I start doing something else, everything acts strange (even when after closing the problem.) 从头开始就可以正常工作,但是一旦我开始做其他事情,一切都会变得很奇怪(即使在解决问题之后也是如此)。

On firefox it will have a "select and highlight all to where the mouse is when I click"; 在firefox上,它将具有“选择并高亮显示我单击时鼠标所在的所有位置”的功能; if I try to type, all numeric characters come out as if the shift button was down and no way around it. 如果我尝试键入,则所有数字字符都会出现,好像Shift键处于按下状态,并且无法绕开它。 If I click on my compiler on the taskbar (wxDev C++), it automatically starts a new instance of the program. 如果单击任务栏(wxDev C ++)上的编译器,它将自动启动该程序的新实例。

That is just the start of the problems, I have a restart my computer to get normal behavior again. 那仅仅是问题的开始,我重新启动计算机以再次恢复正常状态。

I figure that I might be using it wrong: 我认为我可能使用错了:

In int WinMain: 在int WinMain中:

keyboardHook = SetWindowsHookEx(WH_KEYBOARD_LL, LowLevelKeyboardProc, hThisInstance, 0);

In the main procedure: 在主要过程中:

case WM_KEY_WPARAM_VK: 
keyid = wParam; // 65 == 'a'
letterid = keyid - 65;
if ('a'+letterid == 'q') {  DoFunction(); }
return 0;

So that when I hit q on the keyboard, the function is called. 这样,当我在键盘上按q时,就会调用该函数。

This is the procedure, I am trying to not lock the keyboard from typing (so I added the extra line.) I cannot figure this out... 这是过程,我试图不锁定键盘以免键入(因此我添加了额外的行。)我无法弄清楚这一点...

LRESULT CALLBACK LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam ) {
  KBDLLHOOKSTRUCT *pKeyBoard = (KBDLLHOOKSTRUCT *)lParam;
  // When a key is pressed
  if (WM_KEYDOWN == wParam) {
    PostMessage(hWnd, WM_KEY_WPARAM_VK, pKeyBoard->vkCode, 0);
    CallNextHookEx(keyboardHook, pKeyBoard->vkCode, 0, 0);
  }
}

Thanks for reading. 谢谢阅读。

You need to put the CallNextHookEx function outside the if statement! 您需要将CallNextHookEx函数放在if语句之外! (and also update it to properly pass wParam and lParam to the next hook) (并对其进行更新,以将wParamlParam正确传递给下一个钩子)

return CallNextHookEx(keyboardHook, pKeyBoard->vkCode, wParam, lParam);

The way you currently have it, your code will block all "key-up" strokes from the rest of the OS, hence the strange behavior. 您目前拥有的方式,您的代码将阻止操作系统其余部分的所有“按键”操作,因此会产生奇怪的行为。

It's absolutely imperative that CallNextHookEx gets called regardless of what you do within the hook. 无论您在钩子中做什么,都必须调用CallNextHookEx这绝对是必要的。 I would also avoid performing any lengthy (blocking) operations while inside your hook. 我还避免在钩子内部执行任何冗长的(阻塞)操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM