避免文本框在附加文本时闪烁
Avoid TextBox flickering while appending text
我有一个带有文本框的 WindowsForm MDI 应用程序,其中显示来自串行端口的文本流。
默认情况下,每次我向其添加文本时,此文本框都会自动滚动到文本框的末尾。
但是我添加了一个停止自动滚动的选项,代码如下:
namespace MyNs
{
public class MyForm
{
void updateTextbox_timerTick(object sender, EventArgs e)
{
int cursorPos = textbox.SelectionStart;
int selectSize = textbox.SelectionLength;
if(!autoscroll)
textbox.SuspendDrawing();
lock(bufferLock)
{
textbox.AppendText(buffer.ToString());
buffer.Clear();
}
if(autoscroll)
{
textbox.Select(textbox.Text.Length, 0);
textbox.ScrollToCaret();
}
else
{
textbox.Select(cursorPos, selectSize);
textbox.ResumeDrawing();
}
}
}
public static class Utils
{
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing(this Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing(this Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
}
}
}
使用我的方法 ResumeDrawing 和 SuspendDrawing 让文本框在附加时保持在他的位置。但这也增加了闪烁的问题。你知道我如何解决这些问题吗?
感谢您的帮助:)
感谢这个问题:Flicker free TextBox
解决方案是在窗体或控件上启用 WS_EX_COMPOSITED
参数。
为此,您只需将其添加到您的表单或派生控件中即可 class:
private const int WS_EX_COMPOSITED = 0x02000000;
protected override CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_COMPOSITED;
return cp;
}
}
别忘了同时启用 DoubleBuffering。
我有一个带有文本框的 WindowsForm MDI 应用程序,其中显示来自串行端口的文本流。
默认情况下,每次我向其添加文本时,此文本框都会自动滚动到文本框的末尾。
但是我添加了一个停止自动滚动的选项,代码如下:
namespace MyNs
{
public class MyForm
{
void updateTextbox_timerTick(object sender, EventArgs e)
{
int cursorPos = textbox.SelectionStart;
int selectSize = textbox.SelectionLength;
if(!autoscroll)
textbox.SuspendDrawing();
lock(bufferLock)
{
textbox.AppendText(buffer.ToString());
buffer.Clear();
}
if(autoscroll)
{
textbox.Select(textbox.Text.Length, 0);
textbox.ScrollToCaret();
}
else
{
textbox.Select(cursorPos, selectSize);
textbox.ResumeDrawing();
}
}
}
public static class Utils
{
[DllImport("user32.dll")]
private static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
private const int WM_SETREDRAW = 11;
public static void SuspendDrawing(this Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, false, 0);
}
public static void ResumeDrawing(this Control parent)
{
SendMessage(parent.Handle, WM_SETREDRAW, true, 0);
}
}
}
使用我的方法 ResumeDrawing 和 SuspendDrawing 让文本框在附加时保持在他的位置。但这也增加了闪烁的问题。你知道我如何解决这些问题吗?
感谢您的帮助:)
感谢这个问题:Flicker free TextBox
解决方案是在窗体或控件上启用 WS_EX_COMPOSITED
参数。
为此,您只需将其添加到您的表单或派生控件中即可 class:
private const int WS_EX_COMPOSITED = 0x02000000;
protected override CreateParams CreateParams {
get {
CreateParams cp = base.CreateParams;
cp.ExStyle |= WS_EX_COMPOSITED;
return cp;
}
}
别忘了同时启用 DoubleBuffering。