简体   繁体   English

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

[英]How to set TextBox cursor position without SelectionStart

I have a Windows Forms textbox with background thread updating its value every second. 我有一个Windows窗体文本框,后台线程每秒更新其值。 If I place cursor inside textbox it will loose its current position at next update. 如果我将光标放在文本框中,它将在下次更新时松开其当前位置。 Same thing with text selection. 文本选择也是如此。

I tried to solve it like that 我试着像那样解决它

    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;
    }

It works good most of the time. 它大部分时间都很好用。 Here is situation when it does not work: 这是不起作用的情况:
1) I place cursor at the end of the text in textbox 1)我将光标放在文本框中文本的末尾
2) press SHIFT and move cursor to the left using <- arrow key 2)按SHIFT键并使用< - 箭头键将光标向左移动
Selection won't work properly. 选择将无法正常工作。

It looks like combination SelectionStart=10 and SelectionLength=1 automatically moves cursor to position 11 (not 10 as I want it to be). 它看起来像组合SelectionStart=10SelectionLength=1自动将光标移动到位置11(不是10,因为我希望它)。

Please let me know if there is anything I can do about it! 如果有什么我可以做的话,请告诉我! I am using Framework.NET 2.0. 我正在使用Framework.NET 2.0。
There must be a way to set cursor position in textbox other then SelectionStart+SelectionLength . 必须有一种方法在文本框中设置光标位置,然后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();

I have found the solution! 我找到了解决方案!

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

Now its working just like it should. 现在它的工作就像它应该的那样。

To set the cursor position in textbox without selection start...! 要在文本框中设置光标位置而不选择开始......!

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