December 5, 2010
In Windows Forms applications progress is typically shown using the standard ProgressBar control provided by the .NET framework. In many cases however, progress is not accurately reported because calculating beforehand the total number of sub steps and their relative duration is not always easy. In any case, in most situations it is enough to provide the user with some visual indication that processing is still ongoing, and the ProgressBar may not be the best option for that.
Most of the alternatives available out there are just too complex for what they offer. Why introduce a new third-party user control or copy a few hundred lines to your code base when the same result can be achieved with just a couple of lines?
The first step is to add a PictureBox to the form where progress shall be reported. Then an image resource pointing to an animated gif must be added to the project's resources file (Resources.resx, by default). Starting the animation when processing starts is as simple as associating the image to the picture box:
this.pictureBox.Image = Properties.Resources.AnimatedImage;
Stopping the animation is achieved by assigning a static image or null to the picture box's Image property:
this.pictureBox.Image = Properties.Resources.StaticImage;
this.pictureBox.Image = null;
The solution is as simple as that but if you want a more complete example of how this technique can be used together with a BackgroundWorker with error handling and cancellation support, just download the sample VS2008 solution.
The sample solution includes an application that when started shows the "ready" indication (1 in the image bellow). Whenever "Start" is clicked the progress indicator starts spinning (2). There are 3 possible processing outcomes: the operation finishes successfully (3); the user cancels the operation (4); an error occurs during some processing step (5).
Some notes about the sample:
- BackgroundWorker instances can only report progress and support cancellation if their WorkerReportsProgress and WorkerSupportsCancellation properties are set to true;
- The "Simulate Error" button can only be tested from Visual Studio if "Enable Just My Code" is unchecked in Tools > Options... > Debugging > General.
If you want to put this technique in practice in your projects Chimply is a very cool site to generate progress indication images. It allows the customization of foreground and background colors, shape sizes, animation speed and so on. Here are some examples: