如何在不使用SelectionStart的情况下设置TextBox光标位置 [英] How to set TextBox cursor position without SelectionStart

查看:114
本文介绍了如何在不使用SelectionStart的情况下设置TextBox光标位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Windows Forms文本框,其背景线程每秒更新一次它的值。
如果我将光标放在文本框中,它将在下次更新时失去其当前位置。

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.

我试图这样解决

    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键,并使用<将光标移到左侧;-箭头键

选择无法正常工作。

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.

它看起来像组合 SelectionStart = 10 SelectionLength = 1 自动将光标移动到位置11(而不是我想要的位置10)。

It looks like combination SelectionStart=10 and SelectionLength=1 automatically moves cursor to position 11 (not 10 as I want it to be).

请告诉我是否有任何办法可以解决!我正在使用Framework.NET 2.0。

SelectionStart + SelectionLength 之外,必须有一种方法可以在文本框中设置光标位置。

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.

推荐答案

我找到了解决方案!

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

现在可以正常工作了。

这篇关于如何在不使用SelectionStart的情况下设置TextBox光标位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆