如何在 WPF/C# 中的不同语言环境键盘上捕获“#"字符? [英] how to capture the '#' character on different locale keyboards in WPF/C#?
问题描述
我的 WPF 应用程序处理键盘按键,特别是 # 和 * 字符,因为它是 VoIP 电话.
My WPF application handles keyboard presses and specifically the # and * character as it is a VoIP phone.
我在使用国际键盘时遇到了错误,尤其是英式英语键盘.通常我会监听 3 键,如果 shift 键修饰符关闭,我们会触发一个事件来做一些事情.但是在英式键盘上,这是£"字符.我发现英国英语键盘有一个专门的#"键.显然我们可以只听那个特定的键,但这并不能解决美国英语的情况,即 shift-3 以及无数其他将它放在其他地方的键盘.
I have a bug though with international keyboards, and in particular the British english keyboard. Normally I listen for the 3 key and if the shift key modifier is down we fire off an event to do stuff. However on the British keyboard this is the '£' character. I found that the UK english keyboard has a dedicated key for '#'. Obviously we could just listen for that particular key, but that doesn't solve the case for US english which is shift-3 and all the countless other keyboards that put it somewhere else.
长话短说,我如何通过按键聆听特定字符,无论是组合键还是单键,并对其做出反应?
Long story short, how do I listen for a particular character from a key press, whether it's a key combo or single key and react to it?
推荐答案
下面的函数 GetCharFromKey(Key key) 可以解决问题.
The function below, GetCharFromKey(Key key) will do the trick.
它使用一系列 win32 调用来解码按下的键:
It uses a series of win32 calls to decode the key pressed:
从以下位置获取 虚拟密钥WPF 密钥
从虚拟键中获取扫描码
这个旧帖子 更详细地描述了它.
This old post describes it in a bit more detail.
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;
}
这篇关于如何在 WPF/C# 中的不同语言环境键盘上捕获“#"字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!