如何在没有选择开始的情况下设置文本框光标位置

wal*_*ruz 5 c# .net-2.0 winforms

我有一个 Windows 窗体文本框,后台线程每秒更新其值。如果我将光标放在文本框中,它将在下次更新时失去当前位置。与文本选择相同。

我试着这样解决

    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;
    }
Run Code Online (Sandbox Code Playgroud)

大多数情况下它运行良好。这是它不起作用的情况:
1) 我将光标放在文本框中文本的末尾
2) 按 SHIFT 并使用 <- 箭头键将光标向左移动
选择将无法正常工作。

它看起来像组合SelectionStart=10SelectionLength=1自动将光标移动到位置 11(不是我想要的 10)。

如果有什么我可以做的,请告诉我!我正在使用 Framework.NET 2.0。
必须有一种方法可以在文本框中设置光标位置,而不是SelectionStart+SelectionLength.

wal*_*ruz 3

我已经找到解决方案了!

        // save current cursor position and selection 
        int start = textBox.SelectionStart;
        int length = textBox.SelectionLength;

        Point point = new Point();
        User32.GetCaretPos(out point);

        // update text
        textBox.Text = value;

        // restore cursor position and selection
        textBox.Select(start, length);
        User32.SetCaretPos(point.X, point.Y);
Run Code Online (Sandbox Code Playgroud)

现在它正常工作了。