不在焦点时响应键盘?(C#,Vista) [英] Respond to keyboard when not in focus? (C#, Vista)

查看:33
本文介绍了不在焦点时响应键盘?(C#,Vista)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个应用程序,无论当前哪个应用程序具有焦点,只要按下 Shift 键就会响应.

I'm trying to write an application that responds whenever the Shift key is pressed, no matter what application currently has focus.

我用 SetWindowsHookEx()GetKeyboardState() 尝试了这个,但是这两种方法只在应用程序的窗口有焦点时才有效.我需要它在全球范围内工作.

I tried this with SetWindowsHookEx() and with GetKeyboardState(), but both of these only work when the application's window has focus. I need it to work globally.

我该怎么做?

推荐答案

提供的答案都没有帮助我解决我的问题,但我自己找到了答案.在这里.

None of the provided answers helped me solve my problem, but I found the answer myself. Here it is.

使用 SetWindowsHookEx()WH_KEYBOARD_LL 是正确的方法.但是,SetWindowsHookEx() 的其他参数不直观:

Using SetWindowsHookEx() with WH_KEYBOARD_LL was the correct approach. However, the other parameters to SetWindowsHookEx() are unintuitive:

  • 最后一个参数 dwThreadId 需要为 0.
  • 倒数第二个参数 hMod 需要指向某个 DLL.我用了User32,它是一个 DLL,无论如何总是被加载并被所有人使用使用 GUI 处理.我从 一篇关于此的 CodeProject 帖子 中得到了这个想法.
  • The last parameter, dwThreadId, needs to be 0.
  • The second-last parameter, hMod, needs to point to some DLL. I used User32, which is a DLL that is always loaded anyway and is used by all processes with a GUI. I got this idea from a CodeProject post about this.

因此,代码看起来有点像这样:

Thus, the code looks a bit like this:

instance = LoadLibrary("User32");
hhook = SetWindowsHookEx(WH_KEYBOARD_LL, hookFunction, instance, 0);

文档不清楚倒数第二个参数.它说:

The documentation is unclear about the second-last parameter. It says:

如果挂钩过程在与当前进程关联的代码中,则 hMod 参数必须设置为 NULL [...].

The hMod parameter must be set to NULL [...] if the hook procedure is within the code associated with the current process.

它没有说明这仅适用于某些类型的钩子,而不适用于 WH_KEYBOARD_LLWH_MOUSE_LL.

It doesn't state that this only applies to some types of hooks, but not to WH_KEYBOARD_LL and WH_MOUSE_LL.

这篇关于不在焦点时响应键盘?(C#,Vista)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆