This tutorial shows you how to change the color of ProgressBar in C# Windows Forms Application.
You can use Win32 API to change Progress Bar style as the following c# code.
public static class ProgressBarColor
{
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr w, IntPtr l);
public static void SetState(this ProgressBar p, int state)
{
SendMessage(p.Handle, 1040, (IntPtr)state, IntPtr.Zero);
}
}
Drag some progress bar controls from the visual studio toolbox to your windows forms application as shown below.
To use it, you can call:
ProgressBarColor.SetState(progressBar1, 2);
Remark the second parameter in SetState
- 1 = normal (green)
- 2 = error (red)
- 3 = warning (yellow)
Or you can custom Progress Bar control by creating a new class then inheriting the ProgressBar class.
namespace CsharpCode
{
public class CustomProgressBar : ProgressBar
{
public CustomProgressBar()
{
this.SetStyle(ControlStyles.UserPaint, true);
}
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);
}
}
}
Don't forget to add using to the below namespace.
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
To create a custom ProgressBar you need to override the OnPaint method, then add the code following to change your ProgressBar color.
progressBar.ForeColor = Color.FromArgb(125, 0, 0);
progressBar.BackColor = Color.FromArgb(170, 0, 0);