Bry*_*yan 14 c# textbox flicker winforms
我的WinForms应用程序有一个TextBox,我将其用作日志文件.我正在附加没有使用闪烁形式的文本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();
}
}
Run Code Online (Sandbox Code Playgroud)
是否有一种更简洁的方法从控件顶部清除不会引起闪烁的文本行?文本框没有ListView具有的BeginUpdate()/ EndUpdate()方法.
TextBox控件是控制台日志的最佳控件吗?
编辑:TextBox闪烁似乎是向上滚动的文本框(当我清除控件顶部的文本时),然后它立即向下滚动到底部. - 这一切都很快发生,所以我只是看到反复的闪烁.
我也刚刚看到这个问题,建议是使用ListBox,但我不知道这是否适用于我的情况,因为(在大多数情况下)我收到了ListBox的一个字符的文本一时间
mka*_*kaj 13
Mathijs的答案对我有用.我稍微修改了它,所以我可以使用任何控件 - 控件扩展:
namespace System.Windows.Forms
{
public static class ControlExtensions
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool LockWindowUpdate(IntPtr hWndLock);
public static void Suspend(this Control control)
{
LockWindowUpdate(control.Handle);
}
public static void Resume(this Control control)
{
LockWindowUpdate(IntPtr.Zero);
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以你需要做的就是:
myTextBox.Suspend();
// do something here.
myTextBox.Resume();
Run Code Online (Sandbox Code Playgroud)
效果很好.所有闪烁停止.
小智 12
我在互联网上找到了一个解决方案:
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool LockWindowUpdate(IntPtr hWndLock);
internal void FillTB(TextBox tb, string mes)
{
try
{
LockWindowUpdate(tb.Handle);
// Do your thingies with TextBox tb
}
finally
{
LockWindowUpdate(IntPtr.Zero);
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于您一次重复且快速地添加(删除)一个字符。一种解决方案是在添加字符时对其进行缓冲,并以更大的间隔(无论字符数量如何)更新文本框,例如每 250 毫秒。
这需要:
另一种选择是每 250 毫秒和 100 个字符使用一次,无论先发生什么。但这可能会使代码更加复杂,而没有任何实际好处。
归档时间: |
|
查看次数: |
19276 次 |
最近记录: |