作者:乌鸦晕倒_767 | 来源:互联网 | 2023-01-03 15:33
Iveimplementedalow-levelkeyboardhookusingSetWindowsHookEx()function.Itworksfineandretu
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.
我使用SetWindowsHookEx()函数实现了一个低级键盘钩子。它工作正常,并返回每次击键的虚拟键码。我可以使用KeyInterop.KeyFromVirtualKey()将此虚拟键代码转换为System.Windows.Input.Key。但目标是在当前键盘布局中获得与此虚拟键代码对应的符号。
I.e. for German layout I want to get "Y" for Key.Z, "Z" for Key.Y.
即对于德语布局我希望得到Key.Z的“Y”,Key.Y的“Z”。
Does anyone can help?
有人可以帮忙吗?
Thank you.
3 个解决方案
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中断了用户的击键(当使用修饰符如'alt + numpad'或德语键盘上的'+'键修饰符)时,导致意外的字母如果需要,可以打印到屏幕上。
Solved my problem by combining @Nejchy's code with ClearKeyboardBuffer method right before running ToUnicodeEx:
在运行ToUnicodeEx之前,将@ Nejchy的代码与ClearKeyboardBuffer方法结合起来解决了我的问题:
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;
}
In your code that does 'ToUnicodeEx':
在你的'ToUnicodeEx'代码中:
var isDeadKey = ClearKeyboardBuffer((uint)aKey, 0, hKd);
if (isDeadKey) return;
user32.ToUnicodeEx((uint)aKey, vkCode, keyboardState, characters, 10, (uint)0, hKd);
Reference: http://www.siao2.com/2006/03/23/558658.aspx http://www.siao2.com/2006/04/06/569632.aspx
参考:http://www.siao2.com/2006/03/23/558658.aspx http://www.siao2.com/2006/04/06/569632.aspx
Also look at his code: https://stackoverflow.com/a/8705696/802848
另请查看他的代码:https://stackoverflow.com/a/8705696/802848