C# 解決窗體閃爍


C# 解決窗體閃爍

題
登錄以投票
在Windows窗體上造成“閃爍”的窗體上有很多控制。造成這種閃爍的原因有兩個:

1.當控件需要被繪制時,Windows發送一個控件兩個消息。第一個(WM_ERASEBKGND)導致背景被繪制(OnPaintBackground),第二個導致前景被繪(WM_PAINT,射擊OnPaint)。首先看到背景,然后當繪圖緩慢時前景變得明顯。Windows窗體使用ControlStyles.OptimizedDoubleBuffer為這種閃爍提供了一個現成的解決方案。

2.有很多控件的表單需要很長時間來繪制。尤其是按鈕控件的默認樣式是昂貴的。一旦你得到了超過50個控件,它開始變得明顯。Form類首先繪制其背景,並在控件需要去的地方留下“漏洞”。當您使用不透明度或透明度鍵屬性時,這些孔通常是白色的,黑色的。然后每個控件都被繪制,填充在洞中。視覺效果是丑陋的,在Windows窗體中沒有現成的解決方案。雙緩沖不能解決它,因為它只適用於單一控制,而不是一組復合控件。

我在SDK頭文件中發現了一個新的Windows風格,可用於Windows XP和(推測)Vista:WS_EX_COMPOSITED。隨着窗體打開窗體,Windows XP將在窗體及其所有子控件上進行雙緩沖。這有效解決了閃爍的第二個原因。這里有一個例子:

using System; 
使用System.Drawing; 
使用System.Windows.Forms; 

命名空間WindowsApplication1 { 
  公共部分類Form1:窗體{ 
    公共Form1(){ 
      InitializeComponent(); 
      for(int ix = 0; ix <30; ++ ix){ 
        for(int iy = 0; iy <30; ++ iy){ 
          Button btn = new Button(); 
          btn.Location = new Point(ix * 10,iy * 10);
          this.Controls.Add(BTN); 
        } 
      } 
    } 
    protected override CreateParams CreateParams { 
      get { 
        CreateParams cp = base.CreateParams; 
        cp.ExStyle | = 0x02000000; 
        返回cp; 
      } 
    } 
  } 


要看到它在工作,最大限度地減少和恢復的形式,並觀察其繪畫行為。注釋cp.ExStyle賦值以查看差異。您只需要復制並粘貼CreateParams屬性即可。

一些注意事項:這不會加速繪畫。繪畫正在發生時,您的表單將保持不可見狀態,然后在完成后彈出屏幕。而當您使用不透明度或透明度鍵屬性時不起作用,當繪畫發生時,表單輪廓將顯示為丑陋的黑色矩形。最好的解決方法是使用計時器將不透明度值增加到99%,以使表單在繪制后可見。

我還沒有嘗試過很多,如果你有使用它的問題,請張貼到這個線程。

http://social.msdn.microsoft.com/forums/en-US/winforms/thread/aaed00ce-4bc9-424e-8c05-c30213171c2c/

        解決辦法很easy:

將以下代碼塊加在父窗體中的任意位置

protected override CreateParams CreateParams

{

get

{

CreateParams cp = base.CreateParams;

cp.ExStyle |= 0x02000000;

return cp;

}

}

原理很簡單,引用以下原話:

 A form that has a lot of controls takes a long time to paint.  Especially the Button control in its default style is expensive.  Once you get over 50 controls, it starts getting noticeable.  The Form class paints its background first and leaves "holes" where the controls need to go.  Those holes are usually white, black when you use the Opacity or TransparencyKey property.  Then each control gets painted, filling in the holes.  The visual effect is ugly and there's no ready solution for it in Windows Forms.  Double-buffering can't solve it as it only works for a single control, not a composite set of controls. 

I discovered a new Windows style in the SDK header files, available for Windows XP and (presumably) Vista: WS_EX_COMPOSITED.  With that style turned on for your form, Windows XP does double-buffering on the form and all its child controls.  

 參考鏈接:https://social.msdn.microsoft.com/Forums/windows/en-US/aaed00ce-4bc9-424e-8c05-c30213171c2c/flickerfree-painting?forum=winforms

                   http://blog.csdn.net/itoccupant/article/details/32334877


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM