如何在WPF中获得适合给定KeyDown事件的字符?
答案 0 :(得分:3)
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 bool GetKeyboardState(byte[] lpKeyState);
[DllImport("user32.dll")]
public static extern uint MapVirtualKey(uint uCode, MapType uMapType);
[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);
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;
}
答案 1 :(得分:2)
试试这个:
var virtualKey = (uint)KeyInterop.VirtualKeyFromKey(e.Key);
var keyCode = MapVirtualKey(virtualKey, 0);
导入功能MapVirtualKey
[DllImport("user32.dll")]
static extern uint MapVirtualKey(uint uCode, uint uMapType);
答案 2 :(得分:0)
并非所有KeyDown事件都对应于单个可见字符 - 例如Backspace和Enter。您必须将事件arg的内容与您想要关联的内容进行比较。例如,在我的US QUERTY键盘上,左上方的键是一个反向标记,但它可能看起来像另一个键盘的其他内容。
答案 3 :(得分:0)
private void UserControl1_KeyDown_1(object sender, KeyEventArgs e)
{
FieldInfo field = e.GetType().GetField
(
"_scanCode",
BindingFlags.NonPublic |
BindingFlags.Instance
);
Int32 scancode = (Int32)field.GetValue(e);
char c = (char)scancode;
}