问题描述
我的 WinForms 应用程序有一个文本框,我将其用作日志文件.我正在使用 TextBox.AppendText(string);
附加文本而没有闪烁的表单,但是当我尝试清除旧文本时(因为控件的 .Text 属性达到 .MaxLength 限制),我变得很糟糕闪烁.
My WinForms application has a TextBox that I'm using as a log file. I'm appending text without the form flickering using TextBox.AppendText(string);
, however when I try to purge old text (as the control's .Text property reaches the .MaxLength limit), I get awful flicker.
我使用的代码如下:
public static void AddTextToConsoleThreadSafe(TextBox textBox, string text)
{
if (textBox.InvokeRequired)
{
textBox.Invoke(new AddTextToConsoleThreadSafeDelegate(AddTextToConsoleThreadSafe), new object[] { textBox, text });
}
else
{
// Ensure that text is purged from the top of the textbox
// if the amount of text in the box is approaching the
// MaxLength property of the control
if (textBox.Text.Length + text.Length > textBox.MaxLength)
{
int cr = textBox.Text.IndexOf("
");
if (cr > 0)
{
textBox.Select(0, cr + 1);
textBox.SelectedText = string.Empty;
}
else
{
textBox.Select(0, text.Length);
}
}
// Append the new text, move the caret to the end of the
// text, and ensure the textbox is scrolled to the bottom
textBox.AppendText(text);
textBox.SelectionStart = textBox.Text.Length;
textBox.ScrollToCaret();
}
}
有没有一种更简洁的方法可以从控件顶部清除不会导致闪烁的文本行?文本框没有 ListView 所具有的 BeginUpdate()/EndUpdate() 方法.
Is there a neater way of purging lines of text from the top of the control that doesn't cause flickering? A textbox doesn't have the BeginUpdate()/EndUpdate() methods that a ListView has.
TextBox 控件甚至是最适合控制台日志的控件吗?
Is a TextBox control even the best suited control for a console log?
TextBox 闪烁似乎是文本框向上滚动到顶部(当我清除控件顶部的文本时),然后它立即向下滚动到底部.- 这一切都发生得很快,所以我只看到反复闪烁.
The TextBox flickering appears to be the textbox scrolling up to the top (while I purge the text at the top of the control), and then it immediately scrolls back down to the bottom. - it all happens very quickly, so I just see repeated flickering.
我也刚刚看到 这个问题,建议是使用 ListBox,但我不知道这是否适用于我的情况,因为(在大多数情况下)我一次接收一个字符的 ListBox 文本.
I've also just seen this question, and the suggestion was to use a ListBox, however I don't know if this will work in my situation, as (in most cases) I'm receiving the text for the ListBox one character at a time.
推荐答案
问题是您一次又一次地快速添加(删除)一个字符.一种解决方案是在添加字符时对其进行缓冲,并以更大的间隔(无论字符量如何)更新文本框,例如每 250 毫秒.
The problem is that you are adding (removing) one character at a time repeatedly and quickly. One solution would be to buffer the characters as they are being added and update the textbox at greater intervals (regardless of the amount of characters), for example, every 250 milliseconds.
这需要:
- 在其中添加字符的数组或堆栈
- 拥有一个计时器,该计时器将调用一个委托,该委托实际上会使用存储在堆栈中的字符进行更新
另一种选择是每 250 毫秒和 100 个字符都使用一次,无论先发生什么.但这可能会使代码更加复杂而没有任何实际好处.
Another option is to use both every 250 ms and 100 chars, whatever happens first. But this would probably complicate the code more without any tangible benefit.
这篇关于更新期间停止文本框闪烁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!