我有一个Windows Forms文本框,背景线程每秒钟更新其值。
如果我将光标放在文本框内,它会在下一次更新时失去当前位置。选择文本也是同样的情况。
我尝试这样解决问题:
protected void SetTextProgrammatically(string value)
{
// save current cursor position and selection
int start = textBox.SelectionStart;
int length = textBox.SelectionLength;
// update text
textBox.Text = value;
// restore cursor position and selection
textBox.SelectionStart = start;
textBox.SelectionLength = length;
}
大多数情况下,它运作良好。但以下情况时不能正常工作:
1)当光标在文本框末尾时
2)按住SHIFT并使用箭头键<-将光标向左移动
选择将无法正常工作。
看起来似乎是组合
SelectionStart = 10
和 SelectionLength = 1
会自动将光标移动到位置11(而不是我想要的10)。如果有解决办法,请告知我!我正在使用Framework.NET 2.0。
必须有一种方法可以设置文本框中的光标位置,而不是使用
SelectionStart + SelectionLength
。
GetCaretPos / SetCaretPos
函数来改进当前行为,但它没有起作用,所以我将其删除了。我不明白GetPositionFromCharIndex
如何帮助我。 - walruz