Search code examples
c#textboxshortcut

How to disable a textbox keyboard shorcuts in c#?


I've just noticed that Textbox have a default shortcut so that whenever you press Ctrl + H, it starts with deleting letters as if you pressed BackSpace.

This can get quite annoying since I want to open a Form whenever Ctrl + H is pressed. Is there any way to stop the backspacing while still being able to use it to open the Windows Form?


Solution

  • CTRL-H is the ASCII BS (Backspace) character.

    You can disable (or redefine) it, since CTRL+H and BackSpace are not exactly the same thing. There are a few examples listed on this question with other keys.

    You need to add the KeyEventHandler in your Form1.Designer.cs like this:

    this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
    

    And in your Form1.cs add this function:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.H && e.Modifiers == Keys.Control)
        {
            //uncomment if ReadOnly is not working
            //e.SuppressKeyPress  = true;
            
            textbox1.ReadOnly = true;
            Form2 form2 = new Form2();
            form2.Show();
            textbox1.ReadOnly = false;
        }
    }