Click here to Skip to main content
Click here to Skip to main content

Don't Flicker! Double Buffer!

By , 31 Jan 2006
 

Introduction

Flickering is a common problem known to everyone who has programmed in the Windows Forms environment. We all know that even the Windows Task Manager flickers when we select a process from the process list.

If you have ever looked around the subject you might have probably noticed that the most common solution to this is Double Buffering.

Explanation

Double Buffer is a technique where we draw all our graphic needs to an image stored in the memory (buffer) and after we are done with all our drawing needs we a draw a complete image from the memory onto the screen. This concentrates the drawing to the screen (an operation that badly effects the performance of the application) to a single operation rather than many small ones.

An easy example to understand this would be to use a ProgressBar that has several layers:

  1. background layer,
  2. border layer,
  3. progress layer,
  4. percent layer.

For each of these layers, we need to call some drawing operation, and after each drawing operation the control redraws itself to the screen. Now, if the refresh rate is low we won't have any problem but if we speed up the refresh rate flickering (blinking) occurs.

We solve this by drawing all the layers to an image that is located in the memory and after drawing all the layers into this image we draw the image onto the screen. This improves the performance dramatically.

Techniques

Note: All of the techniques that are mentioned below are used in the example source code provided with this article except the first one which is from .NET Framework 1.1, and the source code is for .NET Framework 2.0.

Things you should know before we start

  • SetStyle(ControlStyles.AllPaintingInWmPaint, true);

    When a control is painted there are two functions that are called, the OnPaint and the OnPaintBackground. When this flag set, it ignores the OnPaintBackground function and the OnPaint function takes care of drawing both the background and the foreground.

  • SetStyle(ControlStyles.UserPaint, true);

    When this flag is set to true, the control paints itself and is not painted by the system operation.

  • Tip (by Tim McCurdy): SetStyle(ControlStyles.ResizeRedraw, true);

    Setting this flag causes the control to repaint itself when resized.

  • ProgressBar drawing

    For all these examples, I call a function called DrawProgressBar. The parameter passed to it is a Graphics instance that is used for drawing:

    private void DrawProgressBar(Graphics ControlGraphics)
    {
        // draw background
        ControlGraphics.FillRectangle(Brushes.Black, ClientRectangle);
        // draw border
        ControlGraphics.DrawRectangle(Pens.White, ClientRectangle);
        // draw progress 
        ControlGraphics.FillRectangle(Brushes.SkyBlue, 0, 0, 
                this.Width * ProgressBarPercentValue, this.Height);
        // draw percent
        ControlGraphics.DrawString(ProgressBarPercentValue.ToString(), 
                           this.Font, Brushes.Red, 
                           new Point(this.Width / 2, this.Height / 2));
    }

Starting off

  • .NET Framework 1.1 built-in double buffer

    public partial class DoubleBufferedControl : Control
    {
        public DoubleBufferedControl()
        {
            InitializeComponent();
    
            this.SetStyle(
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.DoubleBuffer, true);
        }
    
        protected override void OnPaint(PaintEventArgs pe)
        {
            // we draw the progressbar normally 
            // with the flags sets to our settings
            DrawProgressBar(pe.Graphics);
        }
    }

    This technique comes with .NET Framework 1.1 and provides some double buffer support. From what I have tested, this technique is not very good and I prefer using the manual technique for .NET Framework 1.1 (which will be shown later).

  • .NET Framework 2.0 built-in double buffer

    public class DoubleBufferedControl : Control
    {
        public DoubleBufferedControl()
        {
            InitializeComponent();
    
            this.SetStyle(
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.OptimizedDoubleBuffer, true);
        }
    
        protected override void OnPaint(PaintEventArgs pe)
        {
            // we draw the progressbar normally with 
            // the flags sets to our settings
            DrawProgressBar(pe.Graphics);
        }
    }

    Well, in .NET Framework 2.0 there is a big improvement in the ease and use of double buffering technique. The performance that we get by using this technique is very good and I recommend this for everyone who doesn't want to get into too much of coding.

    I should mention that when we set Control.DoubleBuffered to true, it will set the ControlStyles.AllPaintingInWmPaint and ControlStyles.OptimizedDoubleBuffer to true.

  • The manual solution for .NET Framework 1.1

    What we do here is create the double buffer ourselves and implement it by overriding the OnPaint event of a control or anything else that you might want to use it on:

    public partial class DoubleBufferedControl : Control
    {
        const Bitmap NO_BACK_BUFFER = null;
        const Graphics NO_BUFFER_GRAPHICS = null;
    
        Bitmap BackBuffer;
        Graphics BufferGraphics;
    
        public DoubleBufferedControl()
        {
            InitializeComponent();
            
            Application.ApplicationExit += 
                new EventHandler(MemoryCleanup);
    
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    
            BackBuffer = new Bitmap(this.Width, this.Height);
            BufferGraphics = Graphics.FromImage(BackBuffer);
        }
    
        private void MemoryCleanup(object sender, EventArgs e)
        {
            // clean up the memory
            if (BackBuffer != NO_BACK_BUFFER)
                BackBuffer.Dispose();
    
            if (BufferGraphics != NO_BUFFER_GRAPHICS)
                BufferGraphics.Dispose();
        }
        protected override void OnPaint(PaintEventArgs pe)
        {
            // we draw the progressbar into the image in 
            // the memory
            DrawProgressBar(BufferGraphics);
    
            // now we draw the image into the screen
            pe.Graphics.DrawImageUnscaled(BackBuffer);
        }
    
        private void DoubleBufferedControl_Resize(object sender, 
                                                     EventArgs e)
        {
            if (BackBuffer != NO_BACK_BUFFER)
                BackBuffer.Dispose();
    
            BackBuffer = new Bitmap(this.Width, this.Height);
            BufferGraphics = Graphics.FromImage(BackBuffer);
    
            this.Refresh();
        }
    }
  • The manual solution for .NET Framework 2.0

    In .NET Framework 2.0, we can still use the manual way. Microsoft has provided us with some useful tools to make it even easier. The new tools are BufferedGraphicsContext and BufferedGraphics. BufferedGraphicsContext provides us an alternative buffer instead of the Bitmap that we used in .NET Framework 1.1 and BufferedGraphics handles all the graphics operations like drawing the buffered image to the screen using the Render() function etc:

    public class DoubleBufferedControl : Control
    {
        const BufferedGraphics NO_MANAGED_BACK_BUFFER = null;
    
        BufferedGraphicsContext GraphicManager;
        BufferedGraphics ManagedBackBuffer;
    
        public DoubleBufferedControl()
        {
            InitializeComponent();
            
            Application.ApplicationExit += 
                   new EventHandler(MemoryCleanup);
    
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
    
            GraphicManager = BufferedGraphicsManager.Current;
            GraphicManager.MaximumBuffer = 
                   new Size(this.Width + 1, this.Height + 1);
            ManagedBackBuffer = 
                GraphicManager.Allocate(this.CreateGraphics(), 
                                               ClientRectangle);
        }
    
        private void MemoryCleanup(object sender, EventArgs e)
        {
            // clean up the memory
            if (ManagedBackBuffer != NO_MANAGED_BACK_BUFFER)
                ManagedBackBuffer.Dispose();
        }
        protected override void OnPaint(PaintEventArgs pe)
        {
            // we draw the progressbar into the image in the memory
            DrawProgressBar(ManagedBackBuffer.Graphics);
    
            // now we draw the image into the screen
            ManagedBackBuffer.Render(pe.Graphics);
        }
    
        private void DoubleBufferedControl_Resize(object sender, 
                                                      EventArgs e)
        {
            if (ManagedBackBuffer != NO_MANAGED_BACK_BUFFER)
                BackBufferManagedBackBufferDispose();
    
            GraphicManager.MaximumBuffer = 
                  new Size(this.Width + 1, this.Height + 1);
    
            ManagedBackBuffer = 
                GraphicManager.Allocate(this.CreateGraphics(), 
                                                ClientRectangle);
    
            this.Refresh();
        }
    }

Conclusion

Double buffering is a good and simple to use technique that I think anyone who has ever dealt with some graphics programming should know. I am also glad to see that Microsoft has put up lot of time to improve the GUI performance of the .NET Framework and provided us with some better tools to deal with them instead of wasting our time on writing some improvised code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Gil.Schmidt
Team Leader EZFace
Israel Israel
Member
Web Team Leader

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberMember 36667148 Aug '10 - 20:50 
Flicker free effect example is really good
GeneralA one-line solution using reflectionmemberMember 411054622 Apr '10 - 9:31 
Thanks very much! There's a way to take an existing control and set the style using reflection (where ctl is your control name):
ctl.GetType().GetMethod("SetStyle", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(ctl, new object[] { ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint |ControlStyles.DoubleBuffer, true});

GeneralRe: A one-line solution using reflectionmemberT_H.net28 Apr '10 - 10:25 
I tried this out for a DataGridView flicker problem -- it works great!
Thanks
GeneralManual solutions and flickeringmemberHolger Hoffmann28 Feb '10 - 3:52 
Hi lads,
 
if you want to implement manual double buffering, you have to override the background painting method, too:
 
protected override void OnPaintBackground(PaintEventArgs pevent)
{
    // do nothing
}
 
So long
Holger
GeneralYESmemberbar49_9#18 Jan '10 - 6:39 
I was getting ready to write a graphics test app but you wrote it for me.
Thank you!
GeneralGetting parameter Not valid errormemberprashant_14419 Nov '09 - 2:03 
I am creating a User Control.
I set DoubleBuffering = true from design time.
When i run my application and try to load an image then it shows me the
error saying "Parameter Not valid" on line Application.Run(new Form1());
 
When i set it to false everything is ok.
I also tried your method by writing this line on constructor but same error occurred.
 
this.SetStyle( ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint | ControlStyles.DoubleBuffer, true);
 
Help Needed
thanks,
 
adad

GeneralProblem in GDI+ drawingmemberskvs3 Dec '08 - 21:42 
hi..
I have used the SetStype property that what u have used for BuiltInOptimisedBuffer, but still i have flickering problem..
 
If i open any other window in front of the painted area, it will again repaints the whole area, is there any way to not to effect the painted area, so that we can avoid repainting of that particular region..
GeneralRe: Problem in GDI+ drawingmemberMember 62846609 Aug '09 - 22:54 
Hi,
 
After putting this code in my control, it was still flickering, and I found the solution on another site : there's another parameter to pass to SetStyle (ControlStyles.DoubleBuffer).
 
Replace the SetStyle line by :
this.SetStyle(ControlStyles.DoubleBuffer | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
 
And after that it will work!
 
Thanks for this great article man
QuestionHow do you double buffer the rendering of all form controls? Not just a single control?memberjohnnynine227 Jul '08 - 18:00 
This is a great article on how to double buffer a single control, so that the rendering of the control does not flicker.
 
However I need to double buffer the entire control collection rendering. I use my own transparent image controls on my form which don't paint a background. These images change frequently so the entire control collection needs to be redrawn often. This causes severe flicker as each control is redrawn in the form.
 
How do I double buffer the rendering of all the form controls so that I don't actually see each control being rendered in turn? I basically need each control to be rendered to an in memory graphics buffer, and then when done, render the graphics buffer.
 
Thanks,
Johnny
QuestionRe: How do you double buffer the rendering of all form controls? Not just a single control?memberselin10052 Sep '08 - 21:45 
Did you get an answer for this or find a solution yourself? Because I'm stuck with the same problem. I have created separate event handlers for the same control so any mouse movement will update all the controls, and their draw methods work fine with flicker actually, but when I try to introduce buffering to remove flicker, I lose them completely!
AnswerRe: How do you double buffer the rendering of all form controls? Not just a single control?memberselin10053 Sep '08 - 22:26 
Question withdrawn... Turns out I got the ClientRectangles wrong.
AnswerRe: How do you double buffer the rendering of all form controls? Not just a single control?memberGil.Schmidt26 Oct '08 - 6:23 
i would recommand making a "master" function for drawing all the controls in one time and disabling the drawing of a control by itself, maybe even passing a common buffer for each one of the controls to draw them self onto the buffer and draw the whole buffer in one time by the master function when it's ready.
 
tell me if it helps
Gil
Questionuse double buffer for picturebox ???memberducmanh8615 Nov '07 - 7:23 
How do I have write code, if i want to use double buffer for picturebox in form?Confused | :confused:
AnswerRe: use double buffer for picturebox ???memberGil.Schmidt17 Nov '07 - 23:10 
this code is not for the existing controls but for writing your own custom controls.
from .Net 2 there's a double buffer property for the form (it's writtin in the article) i might help but i wouldn't count on it.
 
hope this helps..

GeneralThank Umemberdr-Wicked20 Feb '07 - 2:10 
subj
 
dr-Wicked

GeneralGarbage Collection & DisposememberTomer Noy3 Feb '07 - 21:31 
Interesting article, however your handling of memory is problematic.
 
It is very unrecommended to have objects register to events from the Application class. It is not commonly known, but when you register to an event, that event keeps a reference to your object. This means that as long as the notifying object remains in memory, your object will NOT be garbage collected. In the case of Application, this means that every instance of your control class will remain in memory until the application is shut down!
 
The proper place to call dispose on any data members that you have on your control is in the control's Dispose method. This method is called when the control's window is destroyed (when its form is closed), or when it is garbage collected.
 
Some might notice that the Dispose method is auto-generated by the designer when you create a new Form or UserControl, but that doesn't mean you can't alter it. If you cut the method out of the *.designer.cs file, and put it in your code, the code generator will not attempt to recreate it.
QuestionHow can make buffer use Metafile!memberquby26 Nov '06 - 4:39 
I have tried your program,it worked well!
But there is still problem to use the bitmap as the backbuffer,When the picture size is tremendous,it waste so many memory,and also can't change the it's size! So I want to replace the Bitmap to the Metafile,but can't make it work!D'Oh! | :doh:
AnswerRe: How can make buffer use Metafile!memberGil_Schmidt26 Nov '06 - 6:02 
hi man what`s up?
 
i`ll love to help but right now i`m travelling in south america for few more months, i`ll be back in march. i don`t deal with any programming right now and i must say that i never used Metafile so i need to check it out to get you an answer. but if you can try to check it out and change the code to see if it works with other formats, the thing is that the data is saved in memory maybe some other format will have better performence but i don`t know about the quality, i guess that it would be better to add some quality picker that would improve the performance instead of high quality graphics (for example a simple progress bar doesn`t need really high quality graphics)
 
well that`s it for now, hasta luego (until later)
GeneralFlicker still seems to existmemberlevyuk12331 Oct '06 - 5:10 
I've tried the techniques above for my .net 2 app and to be honest the flickering is still present. This might have something to do with 2 forms being open both of which have the OnPaint method overridden. I wouldn't have thought that having two forms open would make such a difference but it does.
 
Levy
GeneralRe: Flicker still seems to existmemberGil_Schmidt31 Oct '06 - 5:31 
hi man..
i don't know how did you write the code but i hope that you've looked at the example that i gave here but from what i've tested it's supposed to work better with the double buffer techniques.
anyway right now i'm in south america so i don't have time to check it out, sorry.. Gil
GeneralThanksmemberreinux4 May '06 - 21:32 
The .NET 2.0 stuff saved my day.
 
Thanks Smile | :)
GeneralComposite layered graphicsmemberJaseNet4 Mar '06 - 1:47 
Nice article Gil.
I have a suggestion/question
 

With GDI drawing I use a forground and a background device context for applications where the forground changes regularily. The OnPaint blits the background and then the forground but does no operations on the device contexts. Instead all forground drawing is done on OnDraw and background drawing done in InvaliateControl.
 
As I am new to GDI+ is this something that you could addSmile | :) ? Is there an equivalent to BitBlt that would allow blending of forground and background bitmaps to save repeatably drawing the parts of the control that don't change very often?
 
cheers
Jason
GeneralRe: Composite layered graphicsmemberGil_Schmidt4 Mar '06 - 9:40 
hi JaseNet
 
am.. i don't know if you read the whole article but what double buffering is doing is to draw the the control graphics into an image in the memory and draw it only one time to the "real" surface of the control this improves the performance, if you'll check out the manual way it also disables the OnPaintBackground event so you draw the foreground and background together on a single paint event there isn't really a background just an event of drawing the control. about drawing parts of the control what the manual way gives you is a full control of the paint event so you don't really have to redraw the whole control each time you can write some code that will draw only the parts the you want.
about BitBlt i never had to use it on C# i used it in VB6 but that was long time ago, i'm sure you can use the API with [DllImport] just look around the net..
 
Gil
GeneralRe: Composite layered graphicsmemberJaseNet5 Mar '06 - 1:50 
Hi Gil
Sorry for the confusion. I am fmiliar with double buffering and have read the article. I was looking for a way of extending it using C#. An example of what I was suggesting...
 
If you had a control that was dynamic and displayed a scrolling time history for several events such as the cpu usage display then there is a performance benefit in having the background of the control such as grids, axis, rotated text and watermarks predrawn on another drawing surface. The background surface would only change when the control was resized or for example the axis were changed.
 
The forground drawing surface would only have to contain the dynamic part of the data such as the trace information or rendered display or whatever. This would typically involve displaying a lot of data, say 4 times a second.
As GDI+ is not hardware accelerated it seemed like a good idea to adopt the GDI approach and use two surfaces. For most of the time no drawing would happen on the background surface, only the forground so the cpu is not wasting time constantly drawing all of the display, only the parts that changed.
 
I accept what you are saying about only updating the invalidated regions but in reality this would end up invalidating most, if not all of the display.Smile | :)
 
I have looked at alpha blending the two surfaces but the performance hit on GDI+ is too expensive.
 
thanks
 
Jason
 

GeneralRe: Composite layered graphicsmemberGil_Schmidt5 Mar '06 - 2:01 
hi again
 

well i think this is a good idea but it depends very much on the solution that is being built, and what i aimed for in this article is for the general use of the techniques of double buffering, your suggesting is very good and will surly be fitted in complex graphic project but in simple projects like a progress bar i don't know if it's worth the spending of time for it but on the next update for the article i'll mention it as a possibility.
 
i appreciate your comment Gil

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 1 Feb 2006
Article Copyright 2006 by Gil.Schmidt
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid