How to set TextBox cursor position without SelectionStart

女生的网名这么多〃 提交于 2019-12-07 07:01:20

问题


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.


回答1:


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



回答2:


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.




回答3:


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  */


来源:https://stackoverflow.com/questions/15138165/how-to-set-textbox-cursor-position-without-selectionstart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!