How to put ProgressBar in Button C#

By FoxLearn 7/18/2024 7:48:36 AM   8.87K
In a C# Windows Forms Application, you can't directly embed a ProgressBar into a Button control.

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#

Here's how you can do it:

Create a new Windows Forms Application, then drag and drop the Button, Timer controls from the Visual Studio toolbox to your form designer.

c# progress bar in button

Double-click on the Button control to generate the click event handler allows you to start timer.

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.

private Bitmap _bm;
private int _process = -1;

Adding a tick event handler to the Timer control allows you to draw progress bar.

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.

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.