Search code examples
c#winformsinputblockletter

C# - How can I block the typing of a letter on a key press?


I have a textbox with a OnKeyPress event. In this textbox I wish to input only numbers, and for some specific letters like t or m, I would want to execute a code without that letter being typed in the textbox. Small sample of what I am trying to do:

 //OnKeyPressed:
 void TextBox1KeyDown(object sender, KeyEventArgs e)
    {
        if(e.KeyCode == Keys.T || e.KeyCode == Keys.M) Button1Click(this, EventArgs.Empty);
    }

This unfortunately does not prevent the input of the letter..


Solution

  • Set the SuppressKeyPress property from KeyEventArgs to true, like below:

    private void TextBox1KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.T || e.KeyCode == Keys.M)
        {
            e.SuppressKeyPress = true;
            Button1Click(this, EventArgs.Empty);
        }
    }