Search code examples
c#keyboardraw-input

Looking for a VirtualKey to real char converter function


I'm looking for a function that receives a bunch of VirtualKeys at RawInput from a keyboard. A software pretty similar to a keylogger in C#. Just in case, I searched a damn lot and could find nothing.

Context

  • To capture the event I use KeyPressed.
  • To read the VKey value y access it from e.KeyPressEvent.VKeyName.
  • For alphabetical chars works fine, 'A'->'A', 'B'->'B' and so on.
  • The rest of the chars won't, cases are:
    • A key combination char (which means I have to press more than one key from the keyboard to create them), for example '@'->'AltGr + 2' or '$'->'Shift+5'.
    • A simple number. Whenever I press any number: '2' -> 'D2'.
    • A special char that when I press ' ' -> SPACE.

What I need

Whenever I press a button, I want to receive the exact value of it, not just "SPACE" or "OEMSEMICOLON". I need to get a single char with the value ' ' or ';' or whatever I press.

The simple code

private void OnKeyPressed(object sender, RawInputEventArg e)
{
    KeysConverter kc = new KeysConverter();
    string keyChar = kc.ConvertToString(e.KeyPressEvent.VKeyName);
    Console.WriteLine("You pressed: " + e.KeyPressEvent.VKeyName);
}

Sample from console

Values I get from keyboard vs values I need in ''


Solution

  • such a function with all your specificities does not exist. You have to build the correspondence table.

    the easy way is to build a first array or enum table with 256 virtual keycode or scancode and a second array gives you the right translation virtualKey or scancode to string key

    for example

    public enum Key
    {
            Escape = 1,
            D1,
            D2,
            D3,
            D4,
            D5,
            D6,
            D7,
            D8,
            D9,
            D0
    }
    
    
    private string[] stringCodeMap = {
                "",   //key = 0,
                "",   //key = 1,
                "1",  //D1 = 2,
                "2",  //D2 = 3,
                "3",  //D3 = 4,
                "4",  //D4 = 5,
                "5",  //D5 = 6,
                "6",  //D6 = 7,
                "7",  //D7 = 8,
                "8",  //D8 = 9,
                "9",  //D9 = 10,
                "0",  //D0 = 11
    }
    

    and you could trap the string code with : if scankey is the result of keypressed (virtual key or scancode key)

    string skey = stringCodeMap[(int)scankey];
    

    for multiple keys pressed, Control, shift (left or right).... have their own code