winform闪屏问题解决方案

这里所说的解决方案,其实也没有真正解决闪屏问题,暂时因个人能力和知识方面的原因,还没有找到比较好的解决方案,也请园子里的各位大侠大哥们出手共享大家的解决方案。

      出现闪屏问题的原因:在winform开发中,我们为了实现比较美工的UI界面,常常会使用一些漂亮的背景图片放在Form中或者Panel中,而一个Form中可能有其他好几个背景,它们的颜色图案都不太一样,这样就会出现闪屏的问题,尤其是在一些性能不好的机器上,很容易看出来。

      至于怎么解决,我在网上也找了很久,还是没有找到比较完美点的解决方案,但是用一些其他的方法可以减少闪屏,也就是说闪屏的效果不明显,这样也可以勉强符合要求了,接下来简介以下几种方案。

     1、不使用图片作为背景,而用纯色替代,如果是这样的话,也就不会出现闪屏了,但如果UI上有特别要求的,这条路就行不通了。

     2、重写Panel,然后在Panel中添加背景图片,而不是把背景图片添加到Form中,重写的Panel代码如下:

      

View Code
 1     /// <summary>
 2     /// 一个Panel类,当设置背景图片时,控制其不会闪屏
 3     /// </summary>
 4     public class BackgroundPanel : Panel
 5     {
 6         protected override void OnPaintBackground(PaintEventArgs e)
 7         {
 8             return;
 9         }
10 
11         protected override void OnPaint(PaintEventArgs e)
12         {
13             
14             this.DoubleBuffered = true;
15             if (this.BackgroundImage != null)
16             {
17                 e.Graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
18                 e.Graphics.DrawImage(this.BackgroundImage, new System.Drawing.Rectangle(00this.Width, this.Height),
19                 00this.BackgroundImage.Width, this.BackgroundImage.Height,
20                 System.Drawing.GraphicsUnit.Pixel);
21             }
22             base.OnPaint(e);
23         }
24     }

    3、使用Form的双缓存可以减少闪屏,但效果不明显,可以在Form的Load事件里添加以下代码

       

View Code
1 this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
2 this.SetStyle(ControlStyles.DoubleBuffer, true);
3 this.SetStyle(ControlStyles.UserPaint, true);
4 this.SetStyle(ControlStyles.ResizeRedraw, true);

    

原文地址:https://www.cnblogs.com/liubiaocai/p/2110248.html