重写控件
public partial class ProgressBarEx : System.Windows.Forms.ProgressBar
{
private const int WM_PAINT = 0xf;
private Graphics g;
private bool bs;
//绘制文本
private void DrawText()
{
string s = this.Value + "/" + this.Maximum;
SizeF sz = default(SizeF);
int m = s.Length;
int n = 1;
//计算所需大小
sz = g.MeasureString(s, this.Font, this.Size, StringFormat.GenericDefault, out m,out n);
g.DrawString(s, this.Font, Brushes.Black, (this.Width - sz.Width) / 2f, (this.Height - sz.Height) / 2f);
}
protected override void OnHandleCreated(System.EventArgs e)
{
base.OnHandleCreated(e);
g = Graphics.FromHwnd(this.Handle);
bs = true;
}
protected override void OnHandleDestroyed(System.EventArgs e)
{
base.OnHandleDestroyed(e);
g.Dispose();
bs = false;
}
protected override void WndProc(ref System.Windows.Forms.Message m)
{
base.WndProc(ref m);
switch (m.Msg)
{
case WM_PAINT:
if (bs)
{
DrawText();
}
break;
}
}
}
效果图: