標籤:
本文轉載:https://my.oschina.net/Tsybius2014/blog/659742
我的作業系統是Win7,使用的VS版本是VS2012,文中的代碼都是C#代碼。
這幾天遇到一個問題,即我用一個內嵌圖片的Panel作為Winform應用程式的背景,如所示:
這是一個Winform表單,裡面放置了一個Panel,Dock屬性為Fill,BackgroundImage使用了《少年電世界》2003年第02期的封面圖片,BackgroundImageLayout使用了Stretch。
這個介面現在有兩個問題:
1、在表單第一次被開啟時,背景圖片會出現明顯的閃爍
2、在拉動表單的邊界以調整表單大小時,背景圖片非出現明顯的閃爍
為了處理這一問題,我查了一些資料,也都逐個試過了,下面先說下其中的兩個有代表性方法:
方法1:直接使用雙緩衝
SetStyle(ControlStyles.UserPaint, true);SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.SetStyle(ControlStyles.DoubleBuffer, true); // 雙緩衝
我嘗試著將這段代碼加到表單的建構函式中,並不能解決問題,閃爍依然非常明顯
在MSDN上還有一篇文章《如何通過對表單和控制項使用雙緩衝來減少圖形閃爍》
地址:https://msdn.microsoft.com/zh-cn/library/3t7htc9c%28v=vs.80%29.aspx
這篇文章中也介紹了一個方法使用雙緩衝:
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
這個方法依然不能解決問題。
方法2:重寫CreateParams方法
方法2需要將以下這段代碼放在Form類的代碼內:
protected override CreateParams CreateParams{ get { CreateParams paras = base.CreateParams; paras.ExStyle |= 0x02000000; return paras; }}
這個方法我一開始嘗試的時候一度認為是有效,但使用了一段時間後還是發現了問題:
1、這個方法可以解決問題1,但不能解決問題2
2、這個方法會影響一些其他控制項、組件的重繪(這點才是致命的)
因此,這個方法也不能解決問題。
上面兩個方法都不能解決問題,於是我繼續求助度娘,終於在下面這個頁面找到瞭解決方法:
方法3:封裝Panel類
http://blog.chinaunix.net/uid-14414741-id-2814313.html
這個方法,需要建立一個PanelEnhanced類繼承Panel類,代碼如下:
/// <summary>/// 加強版 Panel/// </summary>class PanelEnhanced : Panel{ /// <summary> /// OnPaintBackground 事件 /// </summary> /// <param name="e"></param> protected override void OnPaintBackground(PaintEventArgs e) { // 重載基類的背景擦除函數, // 解決視窗重新整理,放大,映像閃爍 return; } /// <summary> /// OnPaint 事件 /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { // 使用雙緩衝 this.DoubleBuffered = true; // 背景重繪移動到此 if (this.BackgroundImage != null) { e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; e.Graphics.DrawImage( this.BackgroundImage, new System.Drawing.Rectangle(0, 0, this.Width, this.Height), 0, 0, this.BackgroundImage.Width, this.BackgroundImage.Height, System.Drawing.GraphicsUnit.Pixel); } base.OnPaint(e); }}
將之前我們建立表單中的Panel容器換為我們新封裝的PanelEnhanced容器,將程式的背景圖片放到裡面,再運行程式,程式背景閃爍的問題就完美解決了!
解決Winform應用程式中表單背景閃爍的問題