How to fix the flickering in User controls

后端 未结 12 1652
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:32

In my application i am constantly moving from one control to another. I have created no. of user controls, but during navigation my controls gets flicker. it takes 1 or 2 se

12条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 02:40

    Put the code bellow in your constructor or OnLoad event and if you're using some sort of custom user control that having sub controls, you'll need to make sure that these custom controls are also double buffered (even though in MS documentation they say it's set to true by default).

    If you're making a custom control, you might want to add this flag into your ctor:

    SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
    

    Optionally you can use this code in your Form/Control:

    foreach (Control control in Controls)
    {
        typeof(Control).InvokeMember("DoubleBuffered",
            BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
            null, control, new object[] { true });
    }
    

    We iterating through all the controls in the form/control and accessing their DoubleBuffered property and then we change it to true in order to make each control on the form double buffered. The reason we do reflection here, is because imagine you have a control that has child controls that are not accessible, that way, even if they're private controls, we'll still change their property to true.

    More information about double buffering technique can be found here.

    There is another property I usually override to sort this problem:

    protected override CreateParams CreateParams
    {
        get
        {
            CreateParams parms = base.CreateParams;
            parms.ExStyle |= 0x00000020; // WS_EX_COMPOSITED
            return parms;
        }
    }
    

    WS_EX_COMPOSITED - Paints all descendants of a window in bottom-to-top painting order using double-buffering.

    You can find more of these style flags here.

    Hope that helps!

提交回复
热议问题