在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加载完毕的方法】
推荐阅读
- C#|C# 文件路径操作
- C# 接口实例
- C#|10、接口、抽象、密封、开放封闭原则
- c#|11、C#处理程序异常的技术
- C#|九、C#结构 类 属性
- C#|c# HashtableTo Json 字符串 HashtableToWxJson
- 分表分库(百亿级大数据存储)
- C#|微信小程序开发系列(六)——“处理请求时出错”怎么处理()
- c#做的一个简单的包含实时进度的进度条
- asp.net|c#文件写入与获取post请求数据