I am using the Raw Input API to get a collection of key presses from a keyboard (actually, a magnetic stripe card reader that emulates a keyboard). Here are a couple of code excerpts so you can have an idea of how I'm getting 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 running the code, the card reader outputs the string %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' }
These seem like a collection of actual key presses (duh!) and not the string they represent. Keycode 16 seems to be Shift, so in the card reader's currently configured keyboard mapping a %
character is produced using Shift+5, represented by {16, 53}. The following character, uppercase B
, is Shift+B or {16, 66}. And so it goes for the rest of characters.
Obviously, simply casting these to char
(like I'm doing right now) is not the way to go. So, my question is: How can I translate this array of key presses into the String they represent?