1. 程式人生 > 實用技巧 >C#自定義進度條,帶百分比顯示

C#自定義進度條,帶百分比顯示

C#自帶的進度條控制元件沒有顯示百分比,為此繼承了ProgressBar,重寫一個帶進度百分比的控制元件;沒有載入進度時可以預設顯示文字描述,有進度時改為顯示百分比。

public partial class ProgressBarEx : ProgressBar
    {
        Font fontDefault = new Font("微軟雅黑", 12, FontStyle.Regular, GraphicsUnit.Pixel);
        Brush b = new SolidBrush(Color.Black);
        private bool processing = false
; private string defaultTips = ""; public ProgressBarEx() { this.SetStyle(ControlStyles.UserPaint, true); this.SetStyle(ControlStyles.OptimizedDoubleBuffer, true); this.SetStyle(ControlStyles.AllPaintingInWmPaint, true); }
/// <summary> /// 是否正在載入進度 /// </summary> public bool Processing { get { return processing; } set { processing = value; if (processing) ForeColor = Color.MediumSeaGreen;
else ForeColor = Color.LightGray; } } /// <summary> /// 預設顯示文字 /// </summary> public string DefaultTips { get { return defaultTips; } set { defaultTips = value; } } protected override void OnPaint(PaintEventArgs e) { SolidBrush brush = null; Rectangle bounds = new Rectangle(0, 0, base.Width, base.Height); Bitmap bmp = new Bitmap(bounds.Width,bounds.Height); Graphics gbmp = Graphics.FromImage(bmp); gbmp.FillRectangle(new SolidBrush(this.BackColor), 1, 1, bounds.Width - 2, bounds.Height - 2); bounds.Height -= 4; bounds.Width = ((int)(bounds.Width * (((double)base.Value) / ((double)base.Maximum)))) - 4; brush = new SolidBrush(this.ForeColor); gbmp.FillRectangle(brush, 2, 2, bounds.Width, bounds.Height); brush.Dispose(); string num = ""; if (processing) num = this.Value.ToString() + "%"; else num = defaultTips; var fsize = gbmp.MeasureString(num,fontDefault); gbmp.DrawString(num, fontDefault, b, new PointF(Width / 2 - fsize.Width / 2, Height / 2 - fsize.Height / 2)); e.Graphics.DrawImage(bmp, 0, 0); gbmp.Dispose(); bmp.Dispose(); }
}