C# 获取网页验证码
转载请注明来源:https://www.cnblogs.com/hookjc/
以下方法必需在WebBrowser控件加载网页完成后才可以调用,否则会提示无法将对象引用到实例,切记!!!
public static Image GetRegCodePic(WebBrowser wbMail, string ImgName, string Src, string Alt)
{
HTMLDocument doc = (HTMLDocument)wbMail.Document.DomDocument;//
HTMLBody body = (HTMLBody)doc.body;
IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();
IHTMLControlElement Img;
if (ImgName == "") //如果没有图片的名字,通过Src或Alt中的关键字来取
{
int ImgNum = GetPicIndex(wbMail, Src,Alt);
if (ImgNum == -1) return null;
Img = (IHTMLControlElement)wbMail.Document.Images[ImgNum].DomElement;
}
else
Img = (IHTMLControlElement)wbMail.Document.All[ImgName].DomElement;
rang.add(Img);
rang.execCommand("Copy", false, null);
Image RegImg = Clipboard.GetImage();
Clipboard.Clear();
return RegImg;
}
public static int GetPicIndex(WebBrowser wbMail, string Src, string Alt)
{
int imgnum = -1;
for (int i = 0; i < wbMail.Document.Images.Count; i++) //获取所有的Image元素
{
IHTMLImgElement img = (IHTMLImgElement)wbMail.Document.Images[i].DomElement;
if (Alt == "")
{
if (img.src.Contains(Src)) return i;
}
else
{
if (!string.IsNullOrEmpty(img.alt))
{
if (img.alt.Contains(Alt)) return i;
}
}
}
return imgnum;
}