一般情况下,当ReadyState属性变成READYSTATE_COMPLETE时,Webbrowser控件会通过触发DocumentCompleted事件来指示网页加载完毕。但当加载的网页包含frame时,可能会多次触发该事件,所以不能简单地通过它来判断网页加载完毕。
从微软的官方网站上了解到,并非每个frame都对应了一个DocumentCompleted事件,只有触发了DownloadBegin事件的frame才会有相应的DocumentCompleted事件。另外,最外层的frame总是最后触发DocumentCompleted事件。DocumentCompleted事件具有一个IDispatch *类型的参数,它指示了是在哪个frame上触发的该事件。所以,要判断文档是否加载完毕,只需要判断IDispatch *参数是否是Webbrowser控件的IDispatch。
微软support网站上关于这个问题的说明:
http://support.microsoft.com/?scid=kb%3Ben-us%3B180366&x=9&y=14
这个方法用到了COM相关的知识,在没有现成代码的情况下,对于像我这样从.NET开始进入Windows平台的程序员来讲理解和实现起来都有一定的难度。尤其是.NET 2.0下的Webbrowser控件是对Webbrowser COM组件的不完全封装,我在考察.NET 2.0 Webbrowser的WebBrowserDocumentCompletedEventArgs后并未发现有IDispatch参数或相关参数。不知道是不是在封装过程中被省去了。
希望哪位高手能告诉我如何用C#实现上面的方法,先在此谢过!不过,利用前面提到的最外层的frame总是最后触发DocumentCompleted事件,还有一种更为简单的方法:
1. 引入一个计数器变量,初始值为0;
2. 当Webbrowser控件的DownloadBegin (.NET 2.0中的Navigated)事件发生时对计数器加一;
3. 当Webbrowser控件的DownloadCompleted事件发生时对计数器减一;
4. 计数器减为0说明文档加载完毕
主要代码:


























