如何在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屋!