how to stop flickering C# winforms

前端 未结 16 2293
故里飘歌
故里飘歌 2020-11-28 04:16

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

16条回答
  •  执笔经年
    2020-11-28 04:45

    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

    1. paint things it the right order!
    2. make sure your draw function is < about 1/60th of a second

    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.

提交回复
热议问题