我想防止一个特定字符*
(星号)被输入或粘贴到文本框中。
我试过了:key_press
事件-但是,当用户将星号粘贴到文本框中时,它不会处理这种情况。text_changed
事件-但是,当我删除字符时,光标位置会回到文本的开头。
所以我想知道如何处理它,最好是在一次事件中。
最佳答案
使用更改文本的事件,但是在删除星号之前保存光标的位置(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;
}
}
关于c# - 如何防止用户在文本框中输入特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7741095/