如何在没有 SelectionStart 的情况下设置 TextBox 光标位置

2024-01-18

我有一个 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;
    }

大多数时候它工作得很好。这是它不起作用时的情况:
1)我将光标放在文本框中文本的末尾
2) 按 SHIFT 并使用 选择将无法正常工作。

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

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


//save position
            bool focused = textBox1.Focused;
            int start = textBox1.SelectionStart;
            int len = textBox1.SelectionLength;
            //do your work
            textBox1.Text = "duviubobioub";
            //restore
            textBox1.SelectionStart = start;
            textBox1.SelectionLength = len ;
            textBox1.Select();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在没有 SelectionStart 的情况下设置 TextBox 光标位置 的相关文章

随机推荐