TextBox.AppendText()不自动滚动TextBox、AppendText

2023-09-03 07:48:35 作者:最美不过初阳

我尝试了以下让我的文本框的文字自动滚动:

I tried the following to get my Textbox text to automatically scroll:

是pretty的小事我使用的步骤:

The steps I am using are pretty trivial:

将文本框到窗体。 更改文本框为多。 添加垂直滚动。 使用AppendText()来添加文本到文本框。

文本不会自动滚动,尽管想在这里提到的解决方案:

The text does not automatically scroll, despite trying to solutions mentioned here:

How我自动滚动多行文本框的底部?

这是什么原因,如何解决呢?

What could cause this and how do I fix it?

更新:如果我创建了一个按钮,并用它来调用AppendText()我得到所期望的行为。不过,如果我尝试从窗体的构造函数或load()事件中调用AppendText然后我得到的附加文本,但文本框不滚动。这不是因为我还没有看到任何人在过去发布此问题的一个重复的问题。

UPDATE: If I create a button and use it to call AppendText() I get the desired behavior. However, if I try to call AppendText from the form's constructor or Load() event then I get the appended text but the TextBox does not scroll. This is NOT a duplicate question as I haven't seen anyone post this problem in the past.

推荐答案

由于形式不构造和负载活动期间完全准备好,我不得不用一个任务来得到它的滚动它准备就绪后:

Since the form isn't quite ready during the constructor and load event, I had to use a task to get it to scroll after it becomes ready:

下面是被调用的方法:

void scroll()
{
    this.Invoke(new MethodInvoker(delegate()
        {
            textBox1.SelectionStart = textBox1.Text.Length;
            textBox1.ScrollToCaret();
        }));
}

它得到通过这项工作摆在负载情况下调用:

It gets invoked via this task placed in the load event:

Task task1 = new Task(new Action(scroll));
            task1.Start();