【问题标题】:Delete the last character when a key is pressed on a textbox C#在文本框 C# 上按下键时删除最后一个字符
【发布时间】:2020-02-10 06:49:13
【问题描述】:

我试图阻止用户按相同的键(例如,如果用户在 TextBox 中有“asd”并且用户按“x”,则文本框仍然包含“asd”但不插入“x”),我尝试过使用KeyDownKeyUp,但它会删除最后一个字符,但会插入按下的字符(“asx”会删除“d”)。对不起我的英语不好。

private void txtInsert_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == 104) //I'm trying to delete "h"
        {
            string cadena = txtInsert.Text;
            cadena = cadena.Substring(0, cadena.Length - 1);
            txtInsert.Text = cadena;
            string cadena = "";
            for (int i = 0; i < txtInsert.TextLength-1; i++)
            {
                cadena += txtInsert.Text[i];
            }
            txtInsert.Text = "";
            txtInsert.Text = cadena;
        }
    }

【问题讨论】:

  • 请向我们展示您的代码,以便我们更好地了解发生了什么。
  • 完成@RahulSharma,我希望你能帮助我

标签: c# winforms textbox keypress


【解决方案1】:

尝试KeyPress 事件(这样我们就可以使用char 进行操作,而不是,例如左移)和Handled 按顺序防止用户输入(WinForms 示例):

private void myTextBox_KeyPress(object sender, KeyPressEventArgs e) {
  TextBox box = sender as TextBox;

  // Do nothing if 
  e.Handled = 
    e.KeyChar >= ' ' &&    // key is not control one (e.g. not backspace)
    box.Text.Length >= 3;  // Text Box Text has Length >= 3
}

如果你想阻止添加'h'

  // Do nothing on 'h' character
  e.Handled = e.KeyChar == 'h';

【讨论】:

    猜你喜欢
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 2014-09-15
    • 2014-09-08
    相关资源
    最近更新 更多