KeyEventArgs.Key 到字符 [英] KeyEventArgs.Key to char
问题描述
有什么办法可以把WPF的KeyEventArgs.Key
转成Char
?
Is there any way to convert WPF's KeyEventArgs.Key
to Char
?
我尝试使用 KeyInterop
:
var x = (Char)KeyInterop.VirtualKeyFromKey(e.Key);
对于数字和字母它可以正常工作,但对于其他字符则不行.例如.对于 OemComma
,它返回 '1/4' 而不是 ','.
For numbers and letters it works fine, but for other characters it doesn't.
E.g. for OemComma
it returns '1/4' instead of ','.
我需要它来防止用户在 TextBox
中输入除数字和分隔符(即逗号或句点)以外的任何字符.
I need it to prevent user of inputting into TextBox
any characters except numbers and separators (i.e. commas or periods).
推荐答案
UPDATE:下面的评论找到了原http://stackoverflow.com/a/5826175/187650
UPDATE: the comment below found the original http://stackoverflow.com/a/5826175/187650
在我忘记的地方找到了这个.仍在使用它,不确定它有什么漏洞,但据我所知,它确实有效.
Found this somewhere that I've forgotten. Still using it, not sure what holes it has, but it's worked as far as I know.
public static class KeyEventUtility
{
// ReSharper disable InconsistentNaming
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,
}
// ReSharper restore InconsistentNaming
[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 );
var keyboardState = new byte[256];
GetKeyboardState( keyboardState );
uint scanCode = MapVirtualKey( (uint)virtualKey, MapType.MAPVK_VK_TO_VSC );
var 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;
}
}
这篇关于KeyEventArgs.Key 到字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!