简体   繁体   中英

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..

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);
    }
}

You could always run the TryParse on the keyDown event so as to validate as the data gets entered. It saves the user an additional UI interaction.

private void TextBox1KeyDown(object sender, KeyEventArgs e)
    {
        int i;

        string s = string.Empty;

        s += (char)e.KeyValue;

         if (!(int.TryParse(s, out i)))
        {
            e.SuppressKeyPress = true;
        }
        else if(e.KeyCode == Keys.T || e.KeyCode == Keys.M)
        {
            e.SuppressKeyPress = true;
            Button1Click(this, EventArgs.Empty);
        }             
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM