Simple Progress Bar for WebBrowser Control Navigation
I recently helped someone who asked how to implement a working ProgressBar control and update it based on the progress of a WebBrowser control that is navigating to a URL.
Often I encounter things like this which are very easy to do, yet rarely appear on the web, be it in articles, message boards, or email lists. There have been so many things in C# that I’ve wondered how to do, that required hours (sometimes days) worth of scavenging through Google, MSDN, and my books only to find that the solution was either right under my nose or otherwise incredibly simple. Thus, from now on, even with little things like this, I think I’ll try to make a quick post about them for future reference and for any wandering eyes. There’s a lot of functionality available in .NET, and every once in a blue moon, traversing the MSDN isn’t quite so helpful for just letting you know “what [cool things] can be done.”
So, let’s get started.
First of all, be sure to have your project open and a form ready.
Add a WebBrowser control and adjust its properties as you see fit.
Add a ProgressBar control and adjust its properties as you see fit. For the sake of simplicity, leave the Style property set to Blocks.
My example code will be assuming that the WebBrowser control and ProgressBar control are named webBrowser and progressBar, respectively.
With the WebBrowser control selected, double-click on the event ProgressChanged (assuming you are using Visual C# Express 2008 - if not, make sure your control knows what method to call on the occurrence of the ProgressChanged event). The IDE will take you to the code view of your form and create the following method:
private void webBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
}
Modify your method so that it looks like the following:
private void webBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
progressBar.Maximum = Convert.ToInt32(e.MaximumProgress);
progressBar.Value = Convert.ToInt32(e.CurrentProgress);
}
To explain the above code, we are setting the maximum and setting the value of the ProgressBar control. Although it may not be noticeable at first glance, e.MaximumProgress and e.CurrentProgress return a number of type long. Since the Maximum and Value accept only numbers of type int, we are converting the longs to ints and assigning the properties to their corresponding values.
Enjoy!
[…] example@example.com (noahssite) wrote an interesting post today onHere’s a quick excerptWith the WebBrowser control selected, double-click on the event ProgressChanged (assuming you are using Visual C# Express 2008 - if not, make sure your control knows what method to call on the occurrence of the ProgressChanged event). … […]