gpt4 book ai didi

c# - 在更新期间停止 TextBox 闪烁

转载 作者:可可西里 更新时间:2023-11-01 07:51:27 31 4
gpt4 key购买 nike

我的 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 文本。

最佳答案

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);
}

}
}

所以你需要做的就是:

myTextBox.Suspend();
// do something here.
myTextBox.Resume();

效果很好。所有闪烁停止。

关于c# - 在更新期间停止 TextBox 闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1550293/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com