Search code examples
c#asciikeymapping

Remapping Keys on Application


In my program, I want to be able to maybe input "E" on my keyboard and have it output on the textbox as a different letter, e.g. "F".

What's the most effective way to do this without clashes in sending keys?

    private void textBox_KeyDown(object sender, KeyEventArgs e)
    {
        switch(e.KeyCode)
        {
            case Keys.E:
                e.SuppressKeyPress = true;
                SendKeys.Send("F".ToLowerInvariant());
                break; 
            case Keys.F:
                e.SuppressKeyPress = true;
                SendKeys.Send("E".ToLowerInvariant());
                break;            
        }
    }

I tried using the method above but it ends up clashing and it ends up sending a different letter instead.


Solution

  • You should use the KeyPress event for this, instead of KeyDown/KeyUp event.

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        switch (e.KeyChar.ToString().ToUpper())
        {
            case "E":
                e.KeyChar = 'f';
                break;
            case "F":
                e.KeyChar = 'e';
                break;
        }
    }