Abdallah Nasir
Abdallah Nasir

Reputation: 631

How to get the char input for a certain key, in the current culture or language?

I am designing an on screen keyboard,

I want to change the keys characters to be the same as the char will be printed on the screen after pressing the key

i.e. button A will return "A" in English, "Q" in French

I need a function that returns the string describes the results which its arguments is the key and the current culture

also if it is possible to know what will happen after pressing the shift is a great plus

Upvotes: 1

Views: 1055

Answers (1)

Abdallah Nasir
Abdallah Nasir

Reputation: 631

I have used this code

    [DllImport("user32.dll")]
    public static extern int ToUnicode(uint virtualKeyCode, ScanCodeShort scanCode,
        byte[] keyboardState,
        [Out, MarshalAs(UnmanagedType.LPWStr, SizeConst = 64)]
StringBuilder receivingBuffer,
        int bufferSize, uint flags);

    public static string GetCharsFromKeys(ScanCodeShort keys)
    {
        var buf = new StringBuilder(256);
        var keyboardState = new byte[256];
        GetKeyState(VirtualKeyStates.VK_F3);
        GetKeyboardState(keyboardState);
        keyboardState[(int)System.Windows.Forms.Keys.ControlKey] = 0x00;
        int x = ToUnicode(MapVirtualKey(keys, 1), keys, keyboardState, buf, 256, 0);
        return buf.ToString();
    }


    [DllImport("user32.dll")]
    static extern short GetKeyState(VirtualKeyStates nVirtKey);

    [DllImport("user32.dll")]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool GetKeyboardState(byte[] lpKeyState);

at calling stage, I use GetCharsFromKeys(ScanCodeShort keys) where ScanCodeShort is the scan code, not the virtual code

Upvotes: 2

Related Questions