TextBox.TextChanged后设置SelectionStart异常,如何修复?
解决TextBox去重时光标偏移问题
你的代码核心问题在于:当插入重复字符时,TextChanged触发时文本已经变为插入后的内容(长度+1),你记录的selectionStart是插入后的光标位置,而去重后文本长度回到原长,直接将光标设为插入后的位置就会导致光标右移一位。
修改后的代码
private void textBox_TextChanged(object sender, EventArgs e) { var textBox = sender as TextBox; if (textBox == null) return; int originalSelectionStart = textBox.SelectionStart; string currentText = textBox.Text; string uniqueText = new string(currentText.Distinct().ToArray()); if (uniqueText != currentText) { textBox.Text = uniqueText; // 计算因去重减少的字符数,调整光标位置 int charRemovedCount = currentText.Length - uniqueText.Length; int newSelectionStart = Math.Max(0, originalSelectionStart - charRemovedCount); textBox.Select(newSelectionStart, 0); } }
逻辑说明
- 先获取当前文本(插入后的内容)和光标位置
- 生成去重后的文本,仅当文本确实发生变化时才更新TextBox内容
- 计算去重过程中移除的字符数量,用原光标位置减去这个数量,得到正确的光标位置
- 用
Math.Max(0, ...)确保光标不会超出文本范围(避免出现负数位置)
这样处理后,无论在文本中间插入重复还是不重复的字符,光标都会保持在你插入前的预期位置。
内容的提问来源于stack exchange,提问作者user18860244
相关产品推荐
相关产品推荐

