1. 程式人生 > >C# WinForm解決Panel控制元件中的圖片重新整理時會閃爍的問題

C# WinForm解決Panel控制元件中的圖片重新整理時會閃爍的問題

     最近在專案開發過程中,使用Panel控制元件顯示座位背景圖,在分屏切換時,發現背景圖會閃爍。在同事的幫助下,通過以下方法解決了:

新建一個類,繼承Panel控制元件類,然後開啟該控制元件的雙重輔助緩衝區,禁止擦除背景,具體請看程式碼:

1、新建一個NewPanel類,繼續Panel控制元件類

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace XC.Contorl
{
    /// <summary>
    /// 用途:防止Panel閃爍
    /// </summary>
    public partial class NewPanel : Panel
    {
        public NewPanel()
        {
            InitializeComponent();

            this.DoubleBuffered = true;//設定本窗體
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 雙緩衝
        }

        public NewPanel(IContainer container)
        {
            container.Add(this);

            InitializeComponent();

            this.DoubleBuffered = true;//設定本窗體
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 雙緩衝
        }
    }
}

2、引用新的Panel控制元件類

   在InitializeComponent() 中,新增以下程式碼:

   this.Panel1 = new XC.Contorl.NewPanel(this.components);

  通過以上發法即可解決圖片閃爍問題,有錯誤或不足之處,望批評指正!