How To Prevent Flickering In GDI+

While developing windows forms application, I often met a situation to draw things on a panel or form using GDI+.
To make a useful and fancy UI, zoom in/zoom out combined with drag and move (pan) of drawing area are required often.
The challenge is that I observed lots of flickering while drag and move or zoom in/out of lots of polygons.
My favorite implementation of these is using the State pattern which defines different states and each state holds necessary event handlers responsible for each mouse actions like button down, move, button up and click.
By the limitation of Win Forms, we need to redraw whole area everytime we wanted to move or update drawings.
Flickering happens right here. Invalidation too often.
Following codes are inserted to prevent this unwanted phenomena.
(Thanks Jun Yang for this tip)

internal class FlickerFreePanel : System.Windows.Forms.Panel
      public FlickerFreePanel()
          : base()
          SetStyle(ControlStyles.AllPaintingInWmPaint, true);
          SetStyle(ControlStyles.DoubleBuffer, true);
          SetStyle(ControlStyles.SupportsTransparentBackColor, true);
          SetStyle(ControlStyles.UserPaint, true);

I defined it as internal class but you can define it outside, any where.
All you need to do is just replace any panel class to draw things with this and there's magic!
I love this trick as long as I need to implement some win forms app with lots of custom drawing.

Add a New Comment
or Sign in as Wikidot user
(will not be published)
- +
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License