How to Custom color of Progress Bar in C#

By FoxLearn 7/17/2024 4:18:52 AM   9.84K
To create a custom background color for a progress bar in C#, you can create a CustomProgressBar class inherit from the ProgressBar control, then override the OnPaint method as shown below.

How to custom background color of Progress Bar in C#

Open your Visual Studio, then create a new Windows Forms project.

Handling the Paint event as shown below.

// c# custom progressbar control
public class CustomProgressBar : ProgressBar
{
    public CustomProgressBar()
    {
        this.SetStyle(ControlStyles.UserPaint, true);
    }

    // c# change background color progress bar
    protected override void OnPaint(PaintEventArgs e)
    {
        Rectangle rec = new Rectangle(0, 0, this.Width, this.Height);
        double scaleFactor = (((double)Value - (double)Minimum) / ((double)Maximum - (double)Minimum));
        if (ProgressBarRenderer.IsSupported)
            ProgressBarRenderer.DrawHorizontalBar(e.Graphics, rec);
        rec.Width = (int)((rec.Width * scaleFactor) - 4);
        rec.Height -= 4;
        LinearGradientBrush brush = new LinearGradientBrush(rec, this.ForeColor, this.BackColor, LinearGradientMode.Vertical);
        e.Graphics.FillRectangle(brush, 2, 2, rec.Width, rec.Height);
    }
}

This custom progress bar will display a gradient brush background and fill the progress portion with the control's ForeColor. You can customize the background color by changing the color in the LinearGradientBrush constructor.

Rebuild your project, then you can see the CustomProgressBar control in your Visual toolbox, drag and drop CustomProgressBar and Button controls from your Visual Studio toolbox to your windows forms application.

You can layout your winform as shown below.

custom color of progress bar in c#

You can also add the custom progress bar to your winform by code.

// c# custom progress bar
CustomProgressBar customProgressBar1 = new CustomProgressBar();
customProgressBar1.Minimum = 0;
customProgressBar1.Maximum = 100;
customProgressBar1.Value = 25;
this.Controls.Add(customProgressBar1);

Finally, Add code behind to handle Form_Load and Start_Click event as shown belown.

private void btnStart_Click(object sender, EventArgs e)
{
    for (int i = 1; i <= 100; i++)
    {
        customProgressBar1.Value = i;
        Thread.Sleep(100);
    }
}

// c# progress bar color
private void Form1_Load(object sender, EventArgs e)
{
    customProgressBar1.ForeColor = Color.FromArgb(120, 0, 0);
    customProgressBar1.BackColor = Color.FromArgb(172, 0, 0);
}

At the Form_Load event you should set the background color for your progress bar. You can then use this custom progress bar control in your form just like a regular progress bar.