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();
        }
}

 效果如下:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM