如何防止用户在文本框中输入特殊字符?

Use*_*404 1 c# winforms

我想阻止将一个特定字符*(星号)输入或粘贴到文本框中.

我试过了:

  1. key_press event - 但它不处理用户将星号粘贴到文本框的情况.
  2. text_changed event - 但是当我删除字符时,光标位置会返回到文本的开头.

所以我想知道如何处理它,最好是在一个事件中.

McK*_*Kay 6

使用文本更改事件,但在删除星号之前保存光标的位置(SelectionStart和SelectionEnd属性),然后重新设置光标位置(减去光标前删除的星号数).

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        var currentText = textBox1.Text;
        var selectionStart = textBox1.SelectionStart;
        var selectionLength = textBox1.SelectionLength;

        int nextAsterisk;
        while ((nextAsterisk = currentText.IndexOf('*')) != -1)
        {
            if (nextAsterisk < selectionStart)
            {
                selectionStart--;
            }
            else if (nextAsterisk < selectionStart + selectionLength)
            {
                selectionLength--;
            }

            currentText = currentText.Remove(nextAsterisk, 1);
        }

        if (textBox1.Text != currentText)
        {
            textBox1.Text = currentText;
            textBox1.SelectionStart = selectionStart;
            textBox1.SelectionLength = selectionLength;
        }
    }
Run Code Online (Sandbox Code Playgroud)