如何自动滚动到多行文本框的底部? [英] How do I automatically scroll to the bottom of a multiline text box?

查看:30
本文介绍了如何自动滚动到多行文本框的底部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .Multiline 属性设置为 true 的文本框.每隔一段时间,我就会向其中添加新的文本行.我希望文本框在添加新行时自动滚动到最底部的条目(最新的条目).我该如何实现?

I have a textbox with the .Multiline property set to true. At regular intervals, I am adding new lines of text to it. I would like the textbox to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added. How do I accomplish this?

推荐答案

每隔一段时间,我就会向其中添加新的文本行.我希望文本框在添加新行时自动滚动到最底部的条目(最新的条目).

At regular intervals, I am adding new lines of text to it. I would like the textbox to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added.

如果您使用 TextBox.AppendText(string text),它会自动滚动到新添加的文本的末尾.如果您在循环中调用它,它可以避免闪烁的滚动条.

If you use TextBox.AppendText(string text), it will automatically scroll to the end of the newly appended text. It avoids the flickering scrollbar if you're calling it in a loop.

它也恰好比连接到 .Text 属性快一个数量级.尽管这可能取决于您调用它的频率;我正在用一个紧密的循环进行测试.

It also happens to be an order of magnitude faster than concatenating onto the .Text property. Though that might depend on how often you're calling it; I was testing with a tight loop.

如果在显示文本框之前调用它,或者如果文本框不可见(例如,在 TabPanel 的不同选项卡中),则不会滚动.请参阅TextBox.AppendText() 不自动滚动.这可能重要也可能不重要,具体取决于您是否需要在用户看不到文本框时自动滚动.

This will not scroll if it is called before the textbox is shown, or if the textbox is otherwise not visible (e.g. in a different tab of a TabPanel). See TextBox.AppendText() not autoscrolling. This may or may not be important, depending on if you require autoscroll when the user can't see the textbox.

在这种情况下,其他答案中的替代方法似乎也不起作用.一种解决方法是对 VisibleChanged 事件执行额外的滚动:

It seems that the alternative method from the other answers also don't work in this case. One way around it is to perform additional scrolling on the VisibleChanged event:

textBox.VisibleChanged += (sender, e) =>
{
    if (textBox.Visible)
    {
        textBox.SelectionStart = textBox.TextLength;
        textBox.ScrollToCaret();
    }
};

<小时>

在内部,AppendText 做这样的事情:

textBox.Select(textBox.TextLength + 1, 0);
textBox.SelectedText = textToAppend;

但是应该没有理由手动进行.

But there should be no reason to do it manually.

(如果你自己反编译它,你会发现它使用了一些可能更有效的内部方法,并且似乎有一个小特殊情况.)

这篇关于如何自动滚动到多行文本框的底部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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