I was trying to use the .NET WebBrowser control and ran into a common problem - how do I tell when a page is really loaded completely? I looked here, and I looked on Google, and I found numerous examples and questions, and so I tried them. And the first place I tried to navigate was http://www.microsoft.com. It didn't go so well.
My code is below. I tried two different approaches - one that used the Url comparison, and one that counted frames. Neither worked as I expected... I got "Form1 - Done - Done - Done - Done" in the Text value, meaning that the page somehow completed several times.
Is there a better, more reliable method to use with complicated web pages?
Here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WebBrowserCompleted
{
public partial class Form1 : Form
{
Uri navTarget = new Uri(@"http://www.microsoft.com");
public Form1()
{
InitializeComponent();
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
//webBrowser1.Navigate(navTarget);
startNavigate(@"http://www.microsoft.com");
}
private int mFrameCount;
private void startNavigate(string url)
{
mFrameCount = 0;
webBrowser1.Navigate(url);
}
private void DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
mFrameCount += 1;
bool done = true;
if (webBrowser1.Document != null)
{
HtmlWindow win = webBrowser1.Document.Window;
if (win.Frames.Count > mFrameCount && win.Frames.Count > 0)
done = false;
}
if (done)
{
Console.WriteLine("Now it is really done");
this.Text = this.Text + " - Done";
}
}
}
}