From OnKeyDown Call OnKeyPress

38 Views Asked by At

for some reason in my environment (CAD) Keypress is not called. So I need to call it manually from overridding KeyDown event. How to convert KeyDown information to a char to pass to KeyPress Event and manage correctly all cases about modifiers, capslock, keyboard layout, ecc? Is there a net framework or low level windows function that does this for me? Thank you

1

There are 1 best solutions below

0
andreat On

I solved like this:

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
    public static extern int ToUnicode(
        uint virtualKeyCode,
        uint scanCode,
        byte[] keyboardState,
        StringBuilder receivingBuffer,
        int bufferSize,
        uint flags
    );

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

    string GetCharsFromKeys(Keys keys)
    {
        var buf = new StringBuilder(256);
        var keyboardState = new byte[256];
        
        GetKeyboardState(keyboardState);

        ToUnicode((uint)keys, 0, keyboardState, buf, 256, 0);
        return buf.ToString();
    }

    private void txt_KeyDown(object sender, KeyEventArgs e)
    {
        string text = GetCharsFromKeys(e.KeyData);
        if (!string.IsNullOrEmpty(text))
        {
            KeyPressEventArgs keyPressEventArgs = new KeyPressEventArgs(text[0]);
            OnKeyPress(keyPressEventArgs);
        }
    }

All keys also using modifiers keys, capslock, alt gr, etc.. works on my keyboard.