Navigate with C# WebBrowser control to a link and wait for full page loading

If you need to build an application that is using the functionality of the WebBrowser control and want to wait until a page is loaded (somehow simulating the synchronous loading of a page), you can use the following piece of code:

private const int sleepTimeMiliseconds = 5;

public void NavigateAndWaitForLoad(WebBrowser wb, string link, int waitTime)
{
    wb.Navigate(link);
    int count = 0;
    while (wb.ReadyState != WebBrowserReadyState.Complete)
    {
        Thread.Sleep(sleepTimeMiliseconds);
        Application.DoEvents();
        count++;
        if (count > waitTime / sleepTimeMiliseconds)
            break;
    }
}

Advertisements

3 Responses to Navigate with C# WebBrowser control to a link and wait for full page loading

  1. Marl Atkins says:

    That’s what I’m doing but the ‘sleep’ seems to be hosing the DocumentCompleted event. Often, it never fires at all.

    If I click from within the browser the event *never* fires.
    Microsoft sure does drop the ball sometimes.

    I sure wish I had a better solution for this.

  2. mark says:

    This is not working if you have flash content on your visited site! any solutions

    • tibileo says:

      Not yet, I’ll take a look at the issue and come back later if I there is any useful solution.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: