简体   繁体   English

当我按 Backspace 时,C# 向 TextBox 输入一个 ASCII 字符

[英]C# inputs an ASCII character to the TextBox when I press Backspace

I have used e.Handled bool of KeyPress event and let e.KeyChar only be D0-D9, ',' and Back.我使用了 KeyPress 事件的 e.Handled bool 并让 e.KeyChar 只有 D0-D9、',' 和 Back。 But then my program started inputting an ASCII character into the TextBox instead of erasing the most recent char when I pressed Backspace.但是随后我的程序开始在 TextBox 中输入一个 ASCII 字符,而不是在我按下 Backspace 时删除最近的字符。 Then I assigned;然后我分配;

if(e.KeyChar == (char)Keys.Back) {textBox1.Text = textBox1.Text + "\\b"}

to erase the most recent char that was inputted.擦除输入的最新字符。 It still decided to input a weird ASCII character instead of erasing anything.它仍然决定输入一个奇怪的 ASCII 字符而不是擦除任何东西。

If you want to allow characters in '0'..'9' range only, while keeping all the other logic intact (for instance, if you select several characters and then press "BackSpace" only selection will be removed, not the last character) you can handle unwanted characters only:如果您只想允许'0'..'9'范围内的字符,同时保持所有其他逻辑不变(例如,如果您选择多个字符然后按“BackSpace”,则只会删除选择,而不是最后一个字符) 您只能处理不需要的字符:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
  e.Handled = e.KeyChar >= ' ' && (e.KeyChar < '0' || e.KeyChar > '9');
}

Note, that e.KeyChar >= ' ' allowes all command characters (BS included)请注意, e.KeyChar >= ' '允许所有命令字符(包括 BS)

this worked:这有效:

if (e.KeyChar == (char)Keys.Back)
        {
            textBox1.Text = textBox1.Text.Substring(0, (textBox1.Text.Length - 1));
        }

Please try with the following code.请尝试使用以下代码。

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar != (char)Keys.Back &&
            (e.KeyChar < (char)Keys.D0 || e.KeyChar > (char)Keys.D9))
        {
            e.Handled = true;
        }
    }

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

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