解決WinForm界面閃爍問題

最近做個功能,根據表數據配置,在窗體上自動生成控件,自動佈局,這個時候是沒有問題的;當窗體大小改變時,控件的位置也要自動調整,這個時候窗體就會出現閃爍,看着很不爽,嚴重影響程序的使用,於是在在網上搜集解決方案,皇天不負有心人,終於把問題解決了,現講方法共享出來。


1、使用雙緩存

SetStyle(ControlStyles.UserPaint, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
SetStyle(ControlStyles.DoubleBuffer, true); //雙緩衝


這是我在網上搜集資料的時候,找到最多的回答,這個有一點用,但是效果確實不太明顯,於是繼續蒐集,終於找到了另外一個能解決實際問題的方案。


2、在主窗體的任意位置重寫CreateParams

protected override CreateParams CreateParams
{
    get
    {
        CreateParams cp = base.CreateParams;
        cp.ExStyle |= 0x02000000;////用雙緩衝從下到上繪製窗口的所有子孫
        return cp;
    }
}


參考資料:http://www.dotblogs.com.tw/rainmaker/archive/2012/02/22/69811.aspx

How to fix the flickering in User controls


http://blog.csdn.net/onejune2013/article/details/7664323

Flicker-free painting


3、爲所有控件設置雙緩存

        private PropertyInfo _PropertyInfo = null;
        
        public IPNWidget()
        {
            InitializeComponent();

            this.DoubleBuffered = true;
            this.SetStyle(
                        ControlStyles.UserPaint |
                        ControlStyles.AllPaintingInWmPaint |
                        ControlStyles.DoubleBuffer, true);

            this._PropertyInfo = this.GetType().GetProperty("DoubleBuffered", BindingFlags.Instance | BindingFlags.NonPublic);
            foreach (Control rootCtrl in this.Controls)
            {
                this._PropertyInfo.SetValue(rootCtrl, true, null);

                if (rootCtrl.HasChildren)
                    SearchControl(rootCtrl);
            }
        }
        
        void SearchControl(Control Ctrl)
        {
            foreach (Control rootCtrl in Ctrl.Controls)
            {
                //Debug.WriteLine(rootCtrl.Name + " 建立DoubleBuffer");
                this._PropertyInfo.SetValue(rootCtrl, true, null);
                if (rootCtrl.HasChildren)
                    SearchControl(rootCtrl);
                else
                    break;
            }
        }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章