Progressbar issue .net Windows 7/Vista

April 10, 2010 by C#  

I noticed a rather annoying issue while working with progressbars in .net & Windows 7/Vista.

The progressbar in my application worked perfectly on Windows XP, but under Windows 7/Vista I found the bar lagging behind the actual percentages passed to the control (The bar eventually catches up).

After some googling I found that this is due to the Aero theme - apparently thanks to delays generated by the animation the theme adds to progressbars (If you disable the Areo theme, everything works fine).

I came up with the following workaround:

using System;
using System.Windows.Forms;
using System.Drawing;

class myProgressBar : ProgressBar
{
    public myProgressBar()
    {
        this.SetStyle(ControlStyles.UserPaint |
            ControlStyles.AllPaintingInWmPaint |
            ControlStyles.OptimizedDoubleBuffer, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        ProgressBarRenderer.DrawHorizontalBar(e.Graphics, this.ClientRectangle);
        Rectangle bounds = new Rectangle
        {
            X = this.ClientRectangle.X,
            Y = this.ClientRectangle.Y,
            Width = (Int32)Math.Floor(((double)this.Value / this.Maximum) * this.ClientRectangle.Width),
            Height = this.ClientRectangle.Height
        };
        bounds.Inflate(-1, -1);
        ProgressBarRenderer.DrawHorizontalChunks(e.Graphics, bounds);
    }
}

We simply inherit from the existing ProgressBar class and override its OnPaint method, visually the progressbar will look the same as the themed one, unfortunately this does however disable the animation effect - but at least the bar keeps up.


Leave a Comment