Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Wait progress bar for long running UI operations

2.33/5 (3 votes)
20 Sep 2011CPOL 44K  
Showing progress bar while performing time consume processes.

Quite commonly, when working with WinForms, we perform time consume processes, for example, search on click, do some business logic, and delete entities from DB on some action.


This is the class you can add into the UI infrastructure for displaying the progress:


C#
public class WaitIndicator : IDisposable
{
    ProgressForm progressForm;
    Thread thread;
    bool disposed = false; //to avoid redundant call
    public WaitIndicator()
    {
        progressForm = new ProgressForm();
        thread = new Thread(_ => progressForm.ShowDialog());
        thread.Start();
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            thread.Abort();
            progressForm = null;
        }
        disposed = true;
    }
}

class ProgressForm : Form
{
    public ProgressForm()
    {
        ControlBox = false;
        ShowInTaskbar = false;
        StartPosition = FormStartPosition.CenterScreen;
        TopMost = true;
        FormBorderStyle = FormBorderStyle.None;
        var progreassBar = new ProgressBar() { Style = ProgressBarStyle.Marquee, 
            Size = new System.Drawing.Size(200, 20), 
            ForeColor = Color.Orange, MarqueeAnimationSpeed = 40 };
        Size = progreassBar.Size;
        Controls.Add(progreassBar);
    }
}

and usage will be like:


C#
using (new WaitIndicator())
{
    //code to process
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)