Windows Forms: Custom Progress Bar with Percentage in C#
By FoxLearn 7/15/2017 7:07:45 PM 13.85K
Create custom progress bar with Percentage in C#.
Step 1: Click 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
Step 2: Design your form as below
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
- How to Send and Receive email in Microsoft Outlook using C#
- How to Print Windows Form in C#
- How to Use Form Load and Button click Event in C#
- How to use Advanced Filter DataGridView in C#
- How to use TagListControl in C#
- How to use Error Provider in C#
- How to Drag and Drop controls in C#
- How to Create a Random Password Generator in C#
Categories
Popular Posts
C# Tutorial
07/20/2024
How to Download Microsoft SQL Server
06/22/2024
What Are RESTful Web Services?
02/19/2024