繁体   English   中英

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

[英]How to set TextBox cursor position without SelectionStart

我有一个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=10SelectionLength=1自动将光标移动到位置11(不是10,因为我希望它)。

如果有什么我可以做的话,请告诉我! 我正在使用Framework.NET 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();

我找到了解决方案!

        // 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);

现在它的工作就像它应该的那样。

要在文本框中设置光标位置而不选择开始......!

textbox1.Select(textbox1.text.length,0); /* ===> End of the textbox  */
  textbox1.Select(0,0);                    /* ===> Start of the textbox  */

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM