How to put ProgressBar in Button C#
By FoxLearn 11/27/2024 11:18:06 AM 9.3K
However, you can achieve a similar effect by creating your own button progress bar, when you click the button, it will be displayed the progress bar with percentage.
How to put ProgressBar in Button using C#
Create a new Windows Forms Application, then drag and drop the Button, Timer controls from the Visual Studio toolbox to your form designer.
Double-click on the Button control to generate the click event handler allows you to start timer.
1 2 3 4 5 6 7 8 9 |
// c# winform progress bar private void btnDownload_Click( object sender, EventArgs e) { timer.Enabled = true ; using (Graphics graphics = Graphics.FromImage(_bm)) { graphics.Clear(btnDownload.BackColor); } } |
Don't forget to declare _bm, _process variables.
1 2 |
private Bitmap _bm; private int _process = -1; |
Adding a tick event handler to the Timer control allows you to draw progress bar.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
private void timer_Tick( object sender, EventArgs e) { const int max_progress = 100; _process++; btnDownload.BeginInvoke( new Action(() => { if (_process > 0) { btnDownload.Text = _process + "%" ; } })); if (_process >= max_progress) { _process = -1; btnDownload.Text = "Download" ; using (Graphics graphics = Graphics.FromImage(_bm)) { graphics.Clear(btnDownload.BackColor); } timer.Enabled = false ; return ; } using (SolidBrush solidBrush = new SolidBrush(Color.FromArgb(30, 40, 160, 60))) { using (Graphics graphics = Graphics.FromImage(_bm)) { float wid = _bm.Width * _process / (max_progress - 5); float hgt = _bm.Height; RectangleF rect = new RectangleF(0, 0, wid, hgt); graphics.FillRectangle(solidBrush, rect); } } btnDownload.Refresh(); } |
Finally, Add a Form_Load event handler as shown below.
1 2 3 4 5 |
private void Form1_Load( object sender, EventArgs e) { _bm = new Bitmap(btnDownload.ClientSize.Width, btnDownload.ClientSize.Height); btnDownload.BackgroundImage = _bm; } |
We will use Timer control to draw progress bar.
This code example demonstrates how to show a ProgressBar when a Button is clicked, perform a lengthy operation, and update the ProgressBar's value accordingly.