Get a string from a set of keystrokes obtained using the Raw Input API

I use the Raw Input API to get a collection of keyboard keystrokes (actually this is a magnetic stripe card reader that emulates a keyboard). Here are a few snippets of code so you can understand how I get the keys.

[StructLayout(LayoutKind.Sequential)]
internal struct RAWKEYBOARD
{
    [MarshalAs(UnmanagedType.U2)]
    public ushort MakeCode;
    [MarshalAs(UnmanagedType.U2)]
    public ushort Flags;
    [MarshalAs(UnmanagedType.U2)]
    public ushort Reserved;
    [MarshalAs(UnmanagedType.U2)]
    public ushort VKey;
    [MarshalAs(UnmanagedType.U4)]
    public uint Message;
    [MarshalAs(UnmanagedType.U4)]
    public uint ExtraInformation;
}

[StructLayout(LayoutKind.Explicit)]
internal struct RAWINPUT
{
    [FieldOffset(0)]
    public RAWINPUTHEADER header;
    [FieldOffset(16)]
    public RAWMOUSE mouse;
    [FieldOffset(16)]
    public RAWKEYBOARD keyboard;
    [FieldOffset(16)]
    public RAWHID hid;
}

Queue<char> MyKeys = new Queue<char>();

// buffer has the result of a GetRawInputData() call
RAWINPUT raw = (RAWINPUT)Marshal.PtrToStructure(buffer, typeof(RAWINPUT));
MyKeys.Enqueue((char)raw.keyboard.VKey);

When the code runs, the card reader displays a line %B40^TEST, but in the MyKeys collection I have the following values:

{ 16 '',  53 '5', 16 '', 66 'B',
  52 '4', 48 '0', 16 '', 54 '6',
  16 '',  84 'T', 16 '', 69 'E',
  16 '',  83 'S', 16 '', 84 'T' }

, (duh!), , . Keycode 16, -, Shift, , , %, Shift + 5, {16, 53}. , B, - Shift + B {16, 66}. .

, char (, ) . , : , ?

+5
1

. , . , , (ushort ) . , , .

class Program
{
    [DllImport("user32.dll")]
    static extern int MapVirtualKey(uint uCode, uint uMapType);

    [DllImport("user32.dll")]
    private static extern int ToAscii(uint uVirtKey, uint uScanCode, byte[] lpKeyState, [Out] StringBuilder lpChar, uint uFlags);

    static void Main(string[] args)
    {
        byte[] keyState = new byte[256];
        ushort[] input = { 16, 53, 16, 66, 52, 48, 16, 54, 16, 84, 16, 69, 16, 83, 16, 84 };
        StringBuilder output = new StringBuilder();

        foreach (ushort vk in input)
            AppendChar(output, vk, ref keyState);

        Console.WriteLine(output);
        Console.ReadKey(true);
    }

    private static void AppendChar(StringBuilder output, ushort vKey, ref byte[] keyState)
    {
        if (MapVirtualKey(vKey, 2) == 0)
        {
            keyState[vKey] = 0x80;
        }
        else
        {
            StringBuilder chr = new StringBuilder(2);
            int n = ToAscii(vKey, 0, keyState, chr, 0);
            if (n > 0)
                output.Append(chr.ToString(0, n));

            keyState = new byte[256];
        }
    }
}
+5

All Articles