gpt4 book ai didi

c# - WPF 错误的 KeyDown ASCII 代码

转载 作者:行者123 更新时间:2023-11-30 13:32:17 24 4
gpt4 key购买 nike

我需要根据 ASCII table 获取键盘按键的数值.由于 WPF 没有内置解决方案,我尝试了几种技巧:

1.这个只给出大写值。

        char res ;
Char.TryParse(e.Key.ToString(),out res);
Debug.WriteLine((int)res);

2 这个,尽管它在许多地方被列为可能的解决方案,但给出了一个完全错误的数字。

        Debug.WriteLine(Convert.ToInt16(e.Key).ToString());

那么如何从 WPF 中的输入中同时获取大写字母和小写字母的 ASCII 码呢?

更新

在这里得到几个答案后,我想强调我的问题。我绝对必须从输入中获取小写和大写的 ASCII 代码。没有硬编码的字符比较或类似的东西。我正在寻找更通用的方法。

最佳答案

查看 KeyEventUtility.GetCharFromKey( e.Key )

更新:抱歉,这是我的一些库代码

    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# - WPF 错误的 KeyDown ASCII 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14818934/

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