【问题标题】:How to prevent TextBox flickering?如何防止文本框闪烁?
【发布时间】:2014-01-06 17:06:56
【问题描述】:

我试图阻止 TextBox 闪烁,但到目前为止没有成功。
TextBox 是多行只读的。

此代码每秒运行几次。文本大约有 10k 个字符。

int ss = txt.SelectionStart;
int sl = txt.SelectionLength;
txt.Text = s;
txt.SelectionStart = ss;
txt.SelectionLength = sl;

研究问题给了我以下可能的解决方案
- 但它们都不起作用。

1) 锁定窗口更新

[System.Runtime.InteropServices.DllImport("user32.dll")]
private static extern bool LockWindowUpdate(IntPtr hWndLock);

//...

LockWindowUpdate(txt.Handle);
txt.Text = someText;
LockWindowUpdate(IntPtr.Zero);

2) 设置样式

this.SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, true);

3) SuspendLayout / ResumeLayout(猜想它与绘画无关——只是尝试一下)

txt.SuspendLayout();
txt.Text = s;
txt.ResumeLayout();

【问题讨论】:

  • 一开始为什么会有闪烁?设置 Text 属性不应导致任何闪烁。你在做什么,有什么问题?
  • 唯一一次我看到闪烁是当您对文本框进行几次小的更新时。如果您正在这样做,也许您应该使用 StringBuilder 对它们进行批处理?

标签: c# winforms textbox flicker doublebuffered


【解决方案1】:

****这是完美的方式。**有一个支持处理IP地址的本机Win32控件

 public class IPTextBox : TextBox
    {
        public IPTextBox() : base()
        {

        }

        protected override CreateParams CreateParams
        {
            get
            {
                new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
                CreateParams cp = base.CreateParams;
                cp.ClassName = "SysIPAddress32";
                return cp;
            }
        }


    }

【讨论】:

  • 对不起,这个问题并不意味着输入 IP 地址。那将是一个特例。这都是关于纯文本框的闪烁。
【解决方案2】:

原来CreateParams的父表单必须使用WS_EX_COMPOSITED标志:

    protected override CreateParams CreateParams {
        get {
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
            CreateParams cp = base.CreateParams;
            cp.ExStyle |= 0x02000000;   // WS_EX_COMPOSITED
            return cp;
        }
    }

【讨论】:

    猜你喜欢
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 2011-09-08
    • 2011-01-30
    • 1970-01-01
    • 2010-09-10
    相关资源
    最近更新 更多