Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF wrong KeyDown ASCII codes

Tags:

c#

wpf

I need to get the numeric values of keyboard keys based on ASCII table .As WPF doesn't have built in solution I have tried several hacks:

1. This one gives only the upper case value.

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

2 This one ,even though it is listed in many places as possible solution , gives a completely wrong number .

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

So how do I get both upper and lower case letter ASCII codes from the input in WPF ?

Update

After getting several answers here I want to emphasize my question .I absolutely must get ASCII codes from the input both for lower and upper case.No hard coded char compare or anything like that.I am looking for more generic way.

like image 498
Michael IV Avatar asked Dec 11 '22 17:12

Michael IV


1 Answers

Look at KeyEventUtility.GetCharFromKey( e.Key )

UPDATE: sorry that was some library code of mine

    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;
    }
like image 191
kenny Avatar answered Jan 01 '23 00:01

kenny