Search code examples
c#keyboardkeyboard-shortcuts

Change key in c#


I need to change keys in c#.

Example : if press on "a" then "b" pressing.

Something like this:

Key.change("a","b"); // a = key , b = value

Please note this : key is static and value is dynamic, it's meaning : key = (always) "a" , value = (can be change) "b" || "c" || "d",etc

So if this problem solving with simply way i really glad.

Thanks and sorry for poor english.


Solution

  • On the Form class, add this method & variable :

    char change = 'b';
    private void ChangeKey(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar=='a')
        {
                e.KeyChar = change;
        }
    }
    

    Then either on Load or Form constructor, subscribe to each of input control you have, manually

    textBox1.KeyPress += ChangeKey;
    textBox2.KeyPress += ChangeKey;
    

    or all of them

     foreach (var item in Controls.OfType<Control>())
     {
        item.KeyPress += ChangeKey;
     }