Home
Map
ProgressBar ExampleUse ProgressBar in Windows Forms with a background thread to indicate progress.
WinForms
This page was last reviewed on Oct 5, 2022.
ProgressBar. This indicates the progress of an operation. ProgressBar is best used on a long-running computation or task. And BackgroundWorker is often used to perform that task.
Getting started. Please add a ProgressBar control to your Windows Forms program by double-clicking on the ProgressBar entry in the Toolbox.
For this example, we also need a BackgroundWorker—add one and then create the event handlers required. We need the Load, DoWork and ProgressChanged event handlers.
BackgroundWorker
Detail In Form1_Load, please add a method call to the RunWorkerAsync method on the BackgroundWorker instance. DoWork will begin.
Detail Here we loop over the numbers 1 through 100. We call the ReportProgress method on the BackgroundWorker instance.
Finally In ProgressChanged, we set the value of the ProgressBar to the ProgressPercentage property of the ProgressChangedEventArgs argument.
using System.ComponentModel; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, System.EventArgs e) { // Start the BackgroundWorker. backgroundWorker1.RunWorkerAsync(); } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { for (int i = 1; i <= 100; i++) { // Wait 100 milliseconds. Thread.Sleep(100); // Report progress. backgroundWorker1.ReportProgress(i); } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { // Change the value of the ProgressBar to the BackgroundWorker progress. progressBar1.Value = e.ProgressPercentage; // Set the text. this.Text = e.ProgressPercentage.ToString(); } } }
Color. One of the useful properties on the ProgressBar is the ForeColor property. This can be set to a Color value to change the color of the bar itself that is drawn on the screen.
Summary. The ProgressBar control is often used with a threading mechanism such as BackgroundWorker. It helps let your users know the application is still active.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Oct 5, 2022 (edit).
Home
Changes
© 2007-2024 Sam Allen.