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

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
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 
GeneralA one-line solution using reflectionmemberMember 411054622 Apr '10 - 9:31 
GeneralRe: A one-line solution using reflectionmemberT_H.net28 Apr '10 - 10:25 
GeneralManual solutions and flickeringmemberHolger Hoffmann28 Feb '10 - 3:52 
GeneralYESmemberbar49_9#18 Jan '10 - 6:39 
GeneralGetting parameter Not valid errormemberprashant_14419 Nov '09 - 2:03 
GeneralProblem in GDI+ drawingmemberskvs3 Dec '08 - 21:42 
GeneralRe: Problem in GDI+ drawingmemberMember 62846609 Aug '09 - 22:54 
QuestionHow do you double buffer the rendering of all form controls? Not just a single control?memberjohnnynine227 Jul '08 - 18:00 
QuestionRe: How do you double buffer the rendering of all form controls? Not just a single control?memberselin10052 Sep '08 - 21:45 
AnswerRe: How do you double buffer the rendering of all form controls? Not just a single control?memberselin10053 Sep '08 - 22:26 
AnswerRe: How do you double buffer the rendering of all form controls? Not just a single control?memberGil.Schmidt26 Oct '08 - 6:23 
Questionuse double buffer for picturebox ???memberducmanh8615 Nov '07 - 7:23 
AnswerRe: use double buffer for picturebox ???memberGil.Schmidt17 Nov '07 - 23:10 
GeneralThank Umemberdr-Wicked20 Feb '07 - 2:10 
GeneralGarbage Collection & DisposememberTomer Noy3 Feb '07 - 21:31 
QuestionHow can make buffer use Metafile!memberquby26 Nov '06 - 4:39 
AnswerRe: How can make buffer use Metafile!memberGil_Schmidt26 Nov '06 - 6:02 
GeneralFlicker still seems to existmemberlevyuk12331 Oct '06 - 5:10 
GeneralRe: Flicker still seems to existmemberGil_Schmidt31 Oct '06 - 5:31 
GeneralThanksmemberreinux4 May '06 - 21:32 
GeneralComposite layered graphicsmemberJaseNet4 Mar '06 - 1:47 
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 
GeneralRe: Composite layered graphicsmemberGil_Schmidt5 Mar '06 - 2:01 
GeneralPossible solution?memberITGFanatic30 Oct '06 - 7:27 
Generalmissing AssemblyInfo.cs from downloadmemberJaseNet4 Mar '06 - 1:02 
GeneralVery nice article!memberrippo7 Feb '06 - 20:57 
GeneralBenchmarkingmemberMikael Wiberg31 Jan '06 - 21:12 
GeneralRe: BenchmarkingmemberGil_Schmidt31 Jan '06 - 21:31 
GeneralRe: Benchmarkingmembergivanfp3 Mar '06 - 10:50 
GeneralRe: BenchmarkingmemberGil_Schmidt3 Mar '06 - 23:30 
GeneralNice with some flawsmemberRobert Rohde29 Jan '06 - 20:05 
GeneralRe: Nice with some flawsmemberGil_Schmidt29 Jan '06 - 22:32 
GeneralControl StylesmemberTim McCurdy29 Jan '06 - 13:30 
GeneralRe: Control StylesmemberGil_Schmidt29 Jan '06 - 22:33 
GeneralRe: Control StylesmemberEchilon29 May '08 - 23:04 
GeneralNice... a couple of minor suggestionsmemberRyan Binns29 Jan '06 - 13:08 
GeneralRe: Nice... a couple of minor suggestionsmemberGil_Schmidt29 Jan '06 - 22:35 
GeneralErrormemberfirmwaredsp29 Jan '06 - 12:26 
GeneralRe: ErrormemberGil_Schmidt29 Jan '06 - 22:36 
GeneralRe: Errormemberfirmwaredsp31 Jan '06 - 21:29 
GeneralGreatmemberPaul M29 Jan '06 - 10:47 
GeneralRe: GreatmemberMatthew Hazlett29 Jan '06 - 10:51 
GeneralRe: Greatmemberantidemon1 Feb '06 - 0:12 

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

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