获取网页验证码并显示在picturebox中

1. 添加引用 

先添加对 Microsoft.mshtml 的引用

使用命名空间 using mshtml; 


2. 核心代码

/// <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();
try
{
Clipboard.SetImage(oldImage);
}
catch
{
}

return numImage;
}

 

3.  引用

HtmlDocument doc = webBrowser1.Document;

//得到验证码图片 
HtmlElement ImgeTag = doc.Images["verifypic"];
Image numPic = GetWebImage(webBrowser1, ImgeTag);
picBoxValidCode.Image = numPic;

你可能感兴趣的:(获取网页验证码并显示在picturebox中)