Windows Forms: Custom Progress Bar with Percentage in C#

Create custom progress bar with Percentage in C#.

Step 1Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "CustomProgressBar" and then click OK

c# progressbar with percentageStep 2: Design your form as below

c# custom control

Step 3: Create a custom control, then modify code as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CustomProgressBar
{
    public partial class MyProgressBar : ProgressBar
    {
        public MyProgressBar()
        {
            InitializeComponent();
            this.SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
        }

        protected override void OnPaint(PaintEventArgs pe)
        {
            //Draw percentage
            Rectangle rect = this.ClientRectangle;
            Graphics g = pe.Graphics;
            ProgressBarRenderer.DrawHorizontalBar(g, rect);
            if (this.Value > 0)
            {
                Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)this.Value / this.Maximum) * rect.Width), rect.Height);
                ProgressBarRenderer.DrawHorizontalChunks(g, clip);
            }
            using (Font f = new Font(FontFamily.GenericMonospace, 10))
            {
                SizeF size = g.MeasureString(string.Format("{0} %", this.Value), f);
                Point location = new Point((int)((rect.Width / 2) - (size.Width / 2)), (int)((rect.Height / 2) - (size.Height / 2) + 2));
                g.DrawString(string.Format("{0} %", this.Value), f, Brushes.Black, location);
            }
            //base.OnPaint(pe);
        }
    }
}

Step 4: Add code to handle your form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CustomProgressBar
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            //Init custom progress bar
            myProgressBar.Minimum = 0;
            myProgressBar.Maximum = 100;
            for(int i = 0; i <= 100; i++)
            {
                myProgressBar.Value = i;
                Thread.Sleep(100);
            }
        }
    }
}

VIDEO TUTORIALS