Search code examples
c#functionreportprogress

Show Progress Visually


I have a function that performs several steps, one at a time, and I would like to display a form or something that tells the user their function is being processed

Basically the function in the Main Form looks like this:

 public void MyFunction ()
{
//Step1, takes aproximately 20 seconds
//Step2, takes 10 seconds
//Step3, takes about 25 seconds
}

So, the idea is to inform the user something is under process, because during Step 1, 2 and 3, the GUI remains unresponsive. I don't want to use a simple ProgressBar, it's an image processing software and there's no space to add a ProgressBar, it should be something that pops up basically. I was thinking on another form but not sure how would that work..

Any ideas on how to do this?

Thank you,

Matias.


Solution

  • To create a simple solution consider this:

    Create a another form (in my case Progress) and put something on it which visualizes the progress. In my case it looks like this:

    Progess form

    The form itself has the FormBorderStyle set to FixedToolWindow and StartPosition set to CenterParent.

    Now change the constructor to the a BackgroundWorker argument and set up the events and start the process.

    public Progress(BackgroundWorker task)
    {
        InitializeComponent();
        task.RunWorkerCompleted += (sender, args) => Close();
        task.ProgressChanged += (sender, args) => pB_progress.Value = args.ProgressPercentage;
        task.RunWorkerAsync();
    }
    

    In the main form just add something like this:

    private void PopupJob()
    {
        var worker = new BackgroundWorker
        {
            WorkerSupportsCancellation = false,
            WorkerReportsProgress = true
        };
        worker.DoWork += OurRealJob;
        new Progress(worker).ShowDialog();
    }
    
    private void OurRealJob(object sender, DoWorkEventArgs doWorkEventArgs)
    {
        var wrk = (BackgroundWorker) sender;
        Thread.Sleep(1000);
        wrk.ReportProgress(30);
        Thread.Sleep(5000);
        wrk.ReportProgress(100);
    }
    

    To show the popup progress thingy simply call PopupJob. The OurRealJob can be replaced with your code.

    When you do it this way, the code will run in the background and the form will stay responsive. Because we are calling Form.ShowDialog() the progress form will be at the front and the main form can not be used until the job is done.