.NET 內建 ProgressBar 僅支援區塊狀 (Standard) 樣式。本文示範繼承 UserControl 繪製平滑漸進樣式進度條,支援 Minimum/Maximum/Value/ProgressBarColor 屬性與 3D 邊框。
SmoothProgressBarUserControl1.cs → SmoothProgressBar.csName 改為 SmoothProgressBarpublic partial class SmoothProgressBar : UserControl
{
private int min = 0, max = 100, val = 0;
private Color barColor = Color.Blue;
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
Invalidate(); // 觸發重繪
}
protected override void OnPaint(PaintEventArgs e)
{
Graphics g = e.Graphics;
using (SolidBrush brush = new SolidBrush(barColor))
{
float percent = (float)(val - min) / (max - min);
Rectangle rect = ClientRectangle;
rect.Width = (int)(rect.Width * percent);
g.FillRectangle(brush, rect);
}
Draw3DBorder(e.Graphics);
}
private void Draw3DBorder(Graphics g)
{
int w = (int)Pens.White.Width;
g.DrawLine(Pens.DarkGray, ClientRectangle.Left, ClientRectangle.Top,
ClientRectangle.Right - w, ClientRectangle.Top);
g.DrawLine(Pens.DarkGray, ClientRectangle.Left, ClientRectangle.Top,
ClientRectangle.Left, ClientRectangle.Bottom - w);
g.DrawLine(Pens.White, ClientRectangle.Left, ClientRectangle.Bottom - w,
ClientRectangle.Right - w, ClientRectangle.Bottom - w);
g.DrawLine(Pens.White, ClientRectangle.Right - w, ClientRectangle.Top,
ClientRectangle.Right - w, ClientRectangle.Bottom - w);
}
// --- 屬性 ---
public int Minimum
{
get => min;
set
{
if (value < 0) value = 0;
if (value > max) { min = value; max = value; }
if (val < min) val = min;
Invalidate();
}
}
public int Maximum
{
get => max;
set
{
if (value < min) min = value;
max = value;
if (val > max) val = max;
Invalidate();
}
}
public int Value
{
get => val;
set
{
int old = val;
val = Math.Max(min, Math.Min(max, value));
// 只重繪差異區域以提升效能
float pNew = (float)(val - min) / (max - min);
float pOld = (float)(old - min) / (max - min);
Rectangle rNew = ClientRectangle; rNew.Width = (int)(rNew.Width * pNew);
Rectangle rOld = ClientRectangle; rOld.Width = (int)(rOld.Width * pOld);
Rectangle update = new Rectangle();
if (rNew.Width > rOld.Width)
{ update.X = rOld.Width; update.Width = rNew.Width - rOld.Width; }
else
{ update.X = rNew.Width; update.Width = rOld.Width - rNew.Width; }
update.Height = Height;
Invalidate(update);
}
}
public Color ProgressBarColor
{
get => barColor;
set { barColor = value; Invalidate(); }
}
}
SmoothProgressBar.dllSmoothProgressBar、一個 Timer (Interval=50)、一個 Button 至表單if (smoothProgressBar1.Value > 0)
{
smoothProgressBar1.Value--;
smoothProgressBar2.Value++;
}
else timer1.Enabled = false;
Invalidate(Rectangle)),效能優於全域重繪