Get a String from a collection of keys presses retrieved using Raw Input API

∥☆過路亽.° 提交于 2019-12-03 15:41:17

After doing some extra research, I found the answer myself. I'm posting it for anyone else reading this. Following is a small test application that demonstrates how to convert a collection of virtual keys (ushort key codes) into its string representation. I'm using the collection described in the question as the input.

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];
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!