1. 程式人生 > >C#解決MDI窗體閃屏的方法 --(arvin推薦)

C#解決MDI窗體閃屏的方法 --(arvin推薦)

最近從師兄手上接了一個C#的專案,需要用到MDI窗體,可是每當我顯示子窗體的時候會有一次“閃爍”,很明顯,看起來非常不爽,查詢許久,知道是每次在show()子窗體的時候都會呼叫子窗體建構函式重繪窗體,其中需要將子窗體的尺寸調整到我在程式中設定的大小,無論我這樣設定,這個視窗大小變化總會在show()的時候顯示出來,我試過網上說的設定雙緩衝、先隱藏窗體等啟動之後再顯示、藉助定時器設定窗體的opacity屬性,可是問題依舊,沒有任何變化,一個偶然的機會找到了微軟的MSDN論壇,發現遇到這個問題的哥們兒還不少,各種國家的程式設計師都有,其中一個哥們提供了一種一勞永逸的解法,徹底的解決了我的問題,天降救世主啊,為了這個問題我茶飯不思了好多天,現將方法分享一下,網上有很多人都有遇到這個問題,可是這是我唯一看到的解法,值得各位碼農收藏啊,原文網址如下,謝謝這位美國小夥子:

解決辦法很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.