Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 531
walruz Avatar asked Feb 28 '13 14:02

walruz


2 Answers

//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();
like image 53
Stefano Altieri Avatar answered Oct 04 '22 03:10

Stefano Altieri


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.

like image 40
walruz Avatar answered Oct 04 '22 02:10

walruz