在文本框 C# 上按下某个键时删除最后一个字符

Delete the last character when a key is pressed on a textbox C#

我正在尝试阻止用户按相同的键(例如,如果用户在 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;
        }
    }

尝试 KeyPress 事件(所以我们有 char 来操作,而不是 key 可以是 left shift ) 和 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';