I have a program that is essentially like a paint application. However, my program has some flickering issues. I have the following line in my code (which should get rid of
I have had the same problem. I was never able to 100% rid myself of the flicker (see point 2), but I used this
protected override void OnPaint(PaintEventArgs e) {}
as well as
this.DoubleBuffered = true;
The main issue for flickering is making sure you
winforms invokes the OnPaint
method each time the form needs to be redrawn. There are many ways it can be devalidated, including moving a mouse cursor over the form can sometimes invoke a redraw event.
And important note about OnPaint
, is you don't start from scratch each time, you instead start from where you were, if you flood fill the background color, you are likely going to get flickering.
Finally your gfx object. Inside OnPaint
you will need to recreate the graphics object, but ONLY if the screen size has changed. recreating the object is very expensive, and it needs to be disposed before it is recreated (garbage collection doesn't 100% handle it correctly or so says documentation). I created a class variable
protected Graphics gfx = null;
and then used it locally in OnPaint
like so, but this was because I needed to use the gfx object in other locations in my class. Otherwise DO NOT DO THIS. If you are only painting in OnPaint, then please use e.Graphics
!!
// clean up old graphics object
gfx.Dispose();
// recreate graphics object (dont use e.Graphics, because we need to use it
// in other functions)
gfx = this.CreateGraphics();
Hope this helps.