我已经使用SetWindowsHookEx()函数实现了一个低级键盘钩子。它工作得很好,每次击键都会返回一个虚拟键码。我可以使用KeyInterop.KeyFromVirtualKey()将这个虚拟密钥代码转换为System.Windows.Input.Key。但目标是在当前键盘布局中获得与此虚拟键码相对应的符号。
例如,对于德国布局,我想将Key.Z设置为"Y“,将Key.Y设置为"Z”。
有人能帮上忙吗?
谢谢。
发布于 2009-08-26 21:53:25
调用GetKeyboardLayout以检索活动布局值,然后执行一些条件循环以获得您想要的结果。
发布于 2012-01-03 05:50:40
你应该看看这个方法GetKeyboardState,GetKeyboardLayout,MapVirtualKeyEx,ToUnicodeEx。
解决方案应该看起来像这样
byte[] keyboardState = new byte[256];
GetKeyboardState(keyboardState);
IntPtr handle = GetKeyboardLayout(0);
uint scanCode = MapVirtualKeyEx(VirtualKeyCode, 0, handle);
StringBuilder stringBuilder = new StringBuilder(2);
int nResultLower = ToUnicodeEx(VirtualKeyCode, scanCode, keyboardState, stringBuilder,
stringBuilder.Capacity, 0, handle);
string output= string.Empty;
if (nResultLower != 0)
{
output = stringBuilder.ToString();
}发布于 2015-02-11 01:02:55
不太确定我们讨论的是相同的场景,但我最近遇到了类似的问题,ToUnicodeEx中断了用户的击键(当使用'alt+numpad‘或在德语键盘上使用'+’键修饰符时),导致意外的字母被打印到屏幕上,如果需要的话。
通过在运行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;
}在执行“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/questions/1164172
复制相似问题