Search code examples
c#winformsdouble-buffering

DoubleBuffered versus SetStyle


I am getting conflicting Google results and I wondered if this can be clarified please?

I have:

typeof(TableLayoutPanel)
   .GetProperty("DoubleBuffered",
      System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
    .SetValue(tableLayoutPanel, true, null);

typeof(TableLayoutPanel)
    .GetMethod("SetStyle",
      System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
      .Invoke(tableLayoutPanel, new object[] { ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true });

But I have been told that if I set DoubleBuffered to true that I do not need to manually set the 3 styles as the system will do that internally. At the moment I am calling both.


Solution

  • From the Reference Source here's the implementation of the DoubleBuffered property:

    protected virtual bool DoubleBuffered {
        get {
            return GetStyle(ControlStyles.OptimizedDoubleBuffer);
        }
        set {
            if (value != DoubleBuffered) {
                if (value) {
                    SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint, value);
                }
                else {
                    SetStyle(ControlStyles.OptimizedDoubleBuffer, value);
                }
            }
        }
    }
    

    (Note that the property is inherited, so you have to go back to the Control class to find it.)