简体   繁体   English

C#-如何阻止按键上的字母键入?

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

I have a textbox with a OnKeyPress event. 我有一个带有OnKeyPress事件的文本框。 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. 在此文本框中,我只希望输入数字,对于某些特定的字母,例如t或m,我想执行一个代码,而无需在文本框中键入该字母。 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: 将KeyEventArgs的SuppressKeyPress属性设置为true,如下所示:

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. 您可以始终在keyDown事件上运行TryParse,以便在输入数据时进行验证。 It saves the user an additional UI interaction. 它为用户节省了额外的UI交互。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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