Monday, October 18, 2010

User Controls: Double Buffering (.NET C#)

I figured I would jump right into things... but it is my first post so I figure I should explain the subject matter. This blog is dedicated to things I have learned while coding. I am primarily a C# programmer that is slightly behind the times. I am still enjoying .NET 2.x.

Now on to the topic of the day: Double Buffering User Controls

I had an old block of code to copy-and-paste around that performed double buffering manually. It created a back buffer to draw into and improved the problems with flickering in my applications. It worked reasonably well. Fortunately my old block of code was made obsolete by 4 lines of very powerful code. (it could be 1 with ORs)

   1:  SetStyle(ControlStyles.AllPaintingInWmPaint, true);
   2:  SetStyle(ControlStyles.UserPaint, true);
   3:  SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
   4:  SetStyle(ControlStyles.Opaque, true);

ControlStyles Enumeration at MSDN

  • AllPaintingInWmPaint and OptimizedDoubleBuffer are actually required together based on the documentation. 
  • Opaque eliminates any background drawing. Depending on your application you may want a background.
  • UserPaint turns over paint responsibility to the control.
The performance actually improved quite significantly over the old manual double buffering. Plus my code is much simpler and ever-so-slightly more logical.

No comments:

Post a Comment