C#判断WebBrowser加载完毕的方法

在C#中使用WebBrowser加载网页有很多便利之处,但多框架和其它因素,使判断最终加载完成一直受到困扰。测试网上的一些方法后,终于比较好的解决了这个问题。
通过环境:VS2015,.Net Framewoek 4.5.1
现在加载有些网页,可能就不触发DocumentCompleted事件,因此在Navigate前,先添加事件WebBrowserDocumentCompletedEventHandler(WB_DocumentCompleted)。




private List eUrlList = new List();
private string url = @"http://www.163.com/";
private static int i = 0;
private void frmBrowser_Load(object sender, EventArgs e)
{
WB.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WB_DocumentCompleted);
WB.ScriptErrorsSuppressed = true;
WB.Navigate(url);
}

private void WB_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
i++;
string eUrl = e.Url.ToString();
eUrlList.Add(string.Format("{0}\t{1}", i, eUrl));
if (eUrl == url || eUrl == url.Insert(4, "s"))
{
MessageBox.Show(string.Join("\n", eUrlList));
}else
{
Application.DoEvents();
}
}

利用参数e可以准确判断。加载完毕,通过i可以看出触发了几次DocumentCompleted事件,每次加载了什么内容。
另外,像http:\\www.baidu.com,加载时会使用https协议,因此判断时加一个条件。
如果多线程,看到一位师傅说必须使用委托,没有亲测,备查。
【C#判断WebBrowser加载完毕的方法】

    推荐阅读