如何在不选中文本的情况下设置文本框光标位置

5

我有一个Windows Forms文本框,背景线程每秒钟更新其值。

如果我将光标放在文本框内,它会在下一次更新时失去当前位置。选择文本也是同样的情况。

我尝试这样解决问题:

    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 = 10 SelectionLength = 1 会自动将光标移动到位置11(而不是我想要的10)。
如果有解决办法,请告知我!我正在使用Framework.NET 2.0。
必须有一种方法可以设置文本框中的光标位置,而不是使用SelectionStart + SelectionLength

it will loose its current position at next update” 这句话的确切含义是什么?你想要达到什么目的? - sloth
这意味着光标会跳转到文本的开头。 - walruz
我希望这个文本框跟其他的文本框一样工作。现在的方式有时候很烦人。我的意思是,我只能从左到右选择文本框中的文字。而当我想要从右往左选择时就无能为力了。 - walruz
我认为你看到的行为是正常的行为。光标始终在选择的末尾,使用箭头键会导致选择长度为0。 - RoadBump
不涉及鼠标事件。我尝试使用GetCaretPos / SetCaretPos函数来改进当前行为,但它没有起作用,所以我将其删除了。我不明白GetPositionFromCharIndex如何帮助我。 - walruz
显示剩余7条评论
3个回答

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
我不看出你的建议和我已经使用的代码之间有什么区别。 - walruz
抱歉..我忘记了Select()。 - Stefano Altieri
不幸的是,这并不是解决方案 - 没有任何改变。我仍然无法从右到左移动光标并选择文本框内的文本。 - walruz
我发布了我用来测试该功能的整个代码,它对我有效,包括从右到左的选择。 - Stefano Altieri
或者一些函数 Select(startIndex, endIndex),它将把光标放置在 endIndex 位置(即使 endIndex < startIndex)。 - walruz
显示剩余2条评论

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

现在它的工作方式如预期一样。

1
在文本框中设置光标位置而不进行选择起点...!
textbox1.Select(textbox1.text.length,0); /* ===> End of the textbox  */
  textbox1.Select(0,0);                    /* ===> Start of the textbox  */

当我使用 Select(0,0)时,它从1开始,留下一个空格。我的掩码是“000-000-0000”。 - Tanner Ornelas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接