【发布时间】:2010-12-05 17:41:42
【问题描述】:
我的 WinForms 应用程序有一个文本框,我将其用作日志文件。我正在使用TextBox.AppendText(string); 附加文本而没有闪烁的表单,但是当我尝试清除旧文本时(因为控件的 .Text 属性达到 .MaxLength 限制),我得到了可怕的闪烁。
我使用的代码如下:
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("\r\n");
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() 方法。
TextBox 控件甚至是最适合控制台日志的控件吗?
编辑:TextBox 闪烁似乎是文本框向上滚动到顶部(当我清除控件顶部的文本时),然后它立即向下滚动到底部。 - 这一切都发生得很快,所以我只看到反复闪烁。
我也刚刚看到 this question,建议使用 ListBox,但我不知道这是否适用于我的情况,因为(在大多数情况下)我收到的文本ListBox 一次一个字符。
【问题讨论】:
-
可能需要将“if”更改为“while”——以防删除第一行文本不足以让新文本适合 TextBox。
-
这篇文章有更多关于这个的信息 - stackoverflow.com/questions/1333393/…
-
其实它有一个非常清晰的解决方案,双缓冲不适用于文本框,所以你应该手动做......
-
Vinko,请发表以上评论作为答案,我可以接受。
-
只需使用 RichTextBox。无闪烁。将 DetectUrls 和 ShortcutsEnabled 属性设置为 FALSE 以提高与 TextBox 的兼容性。真的很好用。
标签: c# winforms textbox flicker