简体   繁体   中英

How to set TextBox cursor position without SelectionStart

I have a Windows Forms textbox with background thread updating its value every second. 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
2) press SHIFT and move cursor to the left using <- arrow key
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).

Please let me know if there is anything I can do about it! I am using Framework.NET 2.0.
There must be a way to set cursor position in textbox other then 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  */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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