gpt4 book ai didi

c# - KeyEventArgs.Key 到 char

转载 作者:可可西里 更新时间:2023-11-01 08:11:00 27 4
gpt4 key购买 nike

有没有办法将 WPF 的 KeyEventArgs.Key 转换为 Char

我尝试使用 KeyInterop:

var x = (Char)KeyInterop.VirtualKeyFromKey(e.Key);

对于数字和字母,它工作正常,但对于其他字符则不然。例如。对于 OemComma,它返回“1/4”而不是“,”。

我需要它来防止用户在 TextBox 中输入除数字和分隔符(即逗号或句点)以外的任何字符。

最佳答案

更新:下面的评论找到了原文 http://stackoverflow.com/a/5826175/187650

在我忘记的地方找到了这个。仍在使用它,不确定它有什么漏洞,但据我所知它是有效的。

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;
}
}

关于c# - KeyEventArgs.Key 到 char,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15359336/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com