问题描述
我已经使用SetWindowsHookEx()函数实现了低级键盘挂钩.它可以正常工作,并为每个击键返回一个虚拟键代码.我可以使用KeyInterop.KeyFromVirtualKey()将此虚拟键代码转换为System.Windows.Input.Key.但是目标是在当前键盘布局中获得与此虚拟按键代码相对应的符号.
I've implemented a low-level keyboard hook using SetWindowsHookEx() function. It works fine and returns a virtual key code for each keystroke. I can convert this virtual key code to a System.Windows.Input.Key using KeyInterop.KeyFromVirtualKey(). But the target is to get a symbol that corresponds to this virtual key code in current keyboard layout.
即对于德国布局,我想为Key.Z获得"Y",为Key.Y获得"Z".
I.e. for German layout I want to get "Y" for Key.Z, "Z" for Key.Y.
有人可以帮忙吗?
谢谢.
推荐答案
不太确定我们是否在谈论同一场景,但是我最近遇到了类似的问题,其中ToUnicodeEx中断了用户的按键(使用'alt + numpad之类的修饰符时'或德文键盘上的'+'键修饰符),从而导致意外的字母被打印到屏幕上(如果需要的话).
Not quite sure we're talking about same scenario, but I recently encountered similar problem where ToUnicodeEx interrupted users' key strokes (when using modifiers like 'alt+numpad' or on German keyboard the '+' key modifier), causing unexpected letters to be printed into screen instead if the desired ones.
通过在运行ToUnicodeEx之前将@Nejchy的代码与ClearKeyboardBuffer方法结合起来解决了我的问题:
Solved my problem by combining @Nejchy's code with ClearKeyboardBuffer method right before running ToUnicodeEx:
private static bool ClearKeyboardBuffer(uint vk, uint sc, IntPtr hkl)
{
StringBuilder sb = new StringBuilder(10);
int rc = -1;
bool isDeadKey = false;
while (rc < 0)
{
rc = user32.ToUnicodeEx(vk, sc, new byte[256], sb, sb.Capacity, 0, hkl);
if (!isDeadKey && rc == -1) isDeadKey = true;
Console.Write(rc);
}
return isDeadKey;
}
在执行"ToUnicodeEx"的代码中:
In your code that does 'ToUnicodeEx':
var isDeadKey = ClearKeyboardBuffer((uint)aKey, 0, hKd);
if (isDeadKey) return;
user32.ToUnicodeEx((uint)aKey, vkCode, keyboardState, characters, 10, (uint)0, hKd);
参考: http://www.siao2.com/2006/03/23/558658. aspx http://www.siao2.com/2006/04/06/569632. aspx
还要看一下他的代码: https://stackoverflow.com/a/8705696/802848
Also look at his code:https://stackoverflow.com/a/8705696/802848
这篇关于使用当前键盘布局截取键盘输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!