WinForm (ProgressBar)進度條顯示百分比


先給大家看一下效果,如下圖

ProgressBar控件.net  目前沒有帶百分比顯示的,要我們自己做一個帶顯示百分比的控件

如轉載請保留原創地址 http://www.luofenming.com/show.aspx?id=ART2018083000001

在這里 長話短說  說重點的

以下是自己繪制帶百分比的ProgressBar的核心代碼

using System.Drawing;
using System.Windows.Forms;
 
namespace 進度條顯示百分比
{
    public class MyProgressBar: ProgressBar//繼承ProgressBar所有功能
    {
        public MyProgressBar()
        {
            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
        }
         
        protected override void OnPaint(PaintEventArgs e)
        {
            Rectangle rect = ClientRectangle;
            Graphics g = e.Graphics;
 
            ProgressBarRenderer.DrawHorizontalBar(g, rect);
            rect.Inflate(-3, -3);
            if (Value > 0)
            {
                var clip = new Rectangle(rect.X, rect.Y, (int)((float)Value / Maximum * rect.Width), rect.Height);
                ProgressBarRenderer.DrawHorizontalChunks(g, clip);
            }
 
            string text = string.Format("{0}%", Value * 100 / Maximum); ;
            using (var font = new Font(FontFamily.GenericSerif, 9))
            {
                SizeF sz = g.MeasureString(text, font);
                var location = new PointF(rect.Width / 2 - sz.Width / 2, rect.Height / 2 - sz.Height / 2 + 2);
                g.DrawString(text, font, Brushes.Black, location);
            }
        }
    }
}

 

也可以通過代碼實例化調用控件,以下是通過代碼實例化調用控件核心代碼

private void button1_Click(object sender, EventArgs e)
{
    ProgressTest();
}
 
private void ProgressTest()
{
    //更多好的實例  請防問www.luofenming.com
    ProgressBar progressBar = new MyProgressBar();
    //progressBar.Dock = DockStyle.Fill;//設置實例化的長寬跟父類一樣
    progressBar.Width = 200;//設置實例化的 寬度
    progressBar.Height = 30;
    panel1.Controls.Add(progressBar);//panel里面添加實例化的控件
 
    //以下是實例下一個Timer  每150毫秒百分比加1
    Timer timer = new Timer { Interval = 150 };
    timer.Tick += (s, e) => progressBar.Value = progressBar.Value % 100 + 1;
    timer.Tick += (s, e) => myProgressBar1.Value = myProgressBar1.Value % 100 + 1;
    timer.Start();
}

 


免責聲明!

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



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