我的 WPF 应用程序处理键盘按下,特别是 # 和 * 字符,因为它是 VoIP 电话。
我在使用国际键盘时遇到了一个错误,尤其是英式英语键盘。通常我会监听 3 键,如果按下 shift 键修饰符,我们会触发一个事件来做一些事情。但是在英式键盘上,这是“£”字符。我发现英国英语键盘有一个专用的“#”键。显然,我们可以只听那个特定的键,但这并不能解决美式英语的情况,即 shift-3 和无数其他将它放在其他地方的键盘。
长话短说,我如何从按键中听到特定字符,无论是组合键还是单键,并对其使用react?
最佳答案
下面的函数 GetCharFromKey(Key key) 可以解决问题。
它使用一系列 win32 调用来解码按下的键:
这old post更详细地描述了它。
public enum MapType : uint
{
MAPVK_VK_TO_VSC = 0x0,
MAPVK_VSC_TO_VK = 0x1,
MAPVK_VK_TO_CHAR = 0x2,
MAPVK_VSC_TO_VK_EX = 0x3,
}
[DllImport("user32.dll")]
public static extern int ToUnicode(
uint wVirtKey,
uint wScanCode,
byte[] lpKeyState,
[Out, MarshalAs(UnmanagedType.LPWStr, SizeParamIndex = 4)]
StringBuilder pwszBuff,
int cchBuff,
uint wFlags);
[DllImport("user32.dll")]
public static extern bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
public static extern uint MapVirtualKey(uint uCode, MapType uMapType);
public static char GetCharFromKey(Key key)
{
char ch = ' ';
int virtualKey = KeyInterop.VirtualKeyFromKey(key);
byte[] keyboardState = new byte[256];
GetKeyboardState(keyboardState);
uint scanCode = MapVirtualKey((uint)virtualKey, MapType.MAPVK_VK_TO_VSC);
StringBuilder stringBuilder = new StringBuilder(2);
int result = ToUnicode((uint)virtualKey, scanCode, keyboardState, stringBuilder, stringBuilder.Capacity, 0);
switch (result)
{
case -1:
break;
case 0:
break;
case 1:
{
ch = stringBuilder[0];
break;
}
default:
{
ch = stringBuilder[0];
break;
}
}
return ch;
}
关于c# - 如何在 WPF/C# 中捕获不同语言环境键盘上的 '#' 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5825820/