C# Winforms: Using a progress bar with Web Browser Control

The .NET web browser provides a number of different events including some which tells when the browser started navigating to a web page and when that navigation completed.

These events are:

private System.Windows.Forms.WebBrowser ItemBrowser;

 

this.ItemBrowser.Navigating += new System.Windows.Forms.WebBrowserNavigatingEventHandler(this.ItemBrowser_Navigating);
this.ItemBrowser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.ItemBrowser_DocumentCompleted);
this.ItemBrowser.Navigated += new System.Windows.Forms.WebBrowserNavigatedEventHandler(this.ItemBrowser_Navigated);

 

This shows the functions are being called at proper events. Now let us come to the code in those functions. The goal is to show a marquee in the status bar when a page is clicked and stop that marquee when navigation is fully complete.

private void ItemBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
    BrowserLabel.Text = "Loading ... ";
    BrowserProgressBar.MarqueeAnimationSpeed = 80;
    BrowserProgressBar.Style = ProgressBarStyle.Marquee;
}

 

I have created two items in the status strip. A Label named BrowserLabel and a progress bar item named BrowserProgressBar. The text property of BrowserLabel is set to “Loading … “ when a hyperlink is created. And to start the marquee we set the style of progress bar to Marquee and its speed to 80. Note that as you increase the AnimationSpeed it will slow down. It will be fastest at 1 and slowest at 100 (I have set 100 as MaxSpeed, you can change that property as well).

Now we need to stop this animation when browsing is complete:

void ItemBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    BrowserProgressBar.MarqueeAnimationSpeed = 0;
    BrowserProgressBar.Style = ProgressBarStyle.Blocks;

    BrowserLabel.Text = "Ready";
}

 

I set the style back to Block and AnimationSpeed to “0”. Style is a property and it can start/stop the animation according to its value so you don’t need to call a “start” function as required in the previous versions. Also the value of Label is reset here.

One function is still remaining:

void ItemBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
    if (!ItemBrowser.IsBusy)
    {
        BrowserProgressBar.MarqueeAnimationSpeed = 0;
        BrowserProgressBar.Style = ProgressBarStyle.Blocks;

        BrowserLabel.Text = "Ready";
    }
}

 

This function is also called when navigation is completed. Although in most cases the DocumentCompleted function is sufficient but bookmark links do not call that function so Navigated function will do in those cases.

 

Share this post : digg it! Facebook it! live it! reddit! technorati! yahoo!