自从用上VS2005后,发现多了个WebBrowser控件(.net 2003中不带),为图方便吧,有好多小工具就用这个写的,慢慢也有点体会了,总结一下,与网友们共享吧。
1、如何获得“打开网页出错”信息 在DocumentCompleted事件中,判断Document.Url.AbsoluteUri中的"res://":标志即可(以前总用e.Url,怪不得总截取不到) if (webBrowser1.Document.Url.AbsoluteUri.IndexOf("res://") > -1) //出错处理 { webBrowser1.Navigate(e.Url); return; } 2、如何使用IHTMLDocument2等MSHTML功能 VS2005中没有完全封装MSHTML中的功能,留了个DomDocument接口。直接引用Microsoft HTML Object Library类库后,就可以操作IHTMLDocument2等复杂的功能了。 如:IHTMLDocument2 doc2 = (IHTMLDocument2)webBrowser1.Document.DomDocument; 3、如何提取网页中的图片,尤其是验证码图等以流方式返回的图片 很多网站一些图片是动态生成了,是从服务器以流方式一点点发过来再组装成图片的。不管是以什么方式,到了客户端,都是完整的。用WebBrowser的好处就在这里,只要管住最终结果就OK了。以下是得到网页上验证码的代码: /// <summary> /// 返回指定WebBrowser中图片<IMG></IMG>中的图内容 /// </summary> /// <param name="WebCtl">WebBrowser控件</param> /// <param name="ImgeTag">IMG元素</param> /// <returns>IMG对象</returns> private Image GetWebImage(WebBrowser WebCtl, HtmlElement ImgeTag) { HTMLDocument doc = (HTMLDocument)WebCtl.Document.DomDocument; HTMLBody body = (HTMLBody)doc.body; IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange(); IHTMLControlElement Img = (IHTMLControlElement)ImgeTag.DomElement; //图片地址Image oldImage = Clipboard.GetImage(); rang.add(Img); rang.execCommand("Copy", false, null); //拷贝到内存 Image numImage = Clipboard.GetImage(); //从 Clipboard中取图 Clipboard.SetImage(oldImage); //还原 return numImage; } |