Smartssolutions

Monday, June 6, 2011

Change the background color of the Windows.Forms.ProgressBar Control

This is a Windows.Forms.ProgressBar control enhancement that helps change the background color of that control as many people request changing the back color of the progressbar control

public class NewProgressBar : ProgressBar
    {
      public NewProgressBar()
      {
        this.SetStyle(ControlStyles.UserPaint, true);
      }
      //I added a new property to the progress bar to let the user change the color
      public Brush BackGroundColor 
      { 
        get; 
        set;
      }

      protected override void OnPaint(PaintEventArgs e)
      {
        Rectangle rec = e.ClipRectangle;

        rec.Width = Convert.ToInt32(Math.Truncate(rec.Width * (Convert.ToDouble(Value) / Maximum))) - 4;
        if (ProgressBarRenderer.IsSupported)
        {
          ProgressBarRenderer.DrawHorizontalBar(e.Graphics, e.ClipRectangle);
        }
        rec.Height = rec.Height - 4;

        if (BackColor==null)
        {
          e.Graphics.FillRectangle(Brushes.YellowGreen, 2, 2, rec.Width, rec.Height);
        }
        else
        {
          e.Graphics.FillRectangle(BackGroundColor, 2, 2, rec.Width, rec.Height);
        }
      }

    }

No comments:

Post a Comment