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

时间:2013-02-28 14:36:46

标签: c# winforms .net-2.0

我有一个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之外的文本框中设置光标位置。

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:3)

我找到了解决方案!

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

现在它的工作正常。

答案 2 :(得分:0)

在文本框中设置光标位置而不选择开始...!

textbox1.Select(textbox1.text.length,0); /* ===> End of the textbox  */
  textbox1.Select(0,0);                    /* ===> Start of the textbox  */
相关问题