簡體   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