文章主旨是使用C++实现对webbrowser或ie浏览器的页面,进行操作。
本次已测试通过,模拟点击一个按钮。
假设按钮在页面是这样显示的:
<input id="btn_ok" type="button" value="OK"/>
1 头文件
#include <mshtmhst.h>
#include <mshtml.h>
#include <atl\atlbase.h>
2 获得IHTMLDocument2对象。
这个前面提过。可以翻越之前的文章。
如果是c++ builder 获取自身form的webbrowser的IHTMLDocument2对象。可参考以下:
IDispatch *dispatch_main=static_cast<IDispatch *>(this->browserMain->Document);
IHTMLDocument2 *doc_main=static_cast<IHTMLDocument2 *>(dispatch_main);
关于IHTMLDocument2对象的一些介绍:
IHtmlDocument2(3)是MSHTML大堂的入口,有了这个,你就可以得到整个html的各个结构节点等了,所以不论你是想做自动填表还是替换脚本,你都先要获得IHtmlDocument2接口,从它开始去解析html。
原文出处:http://www.caogenit.com http://www.caogenit.com/caogenxueyuan/bianchengyuyan/Csharp/1720.html
3 获得IHTMLElementCollection对象。
我理解是页面元素的集合。
获得代码:(前面的章节也介绍过相关代码)
IHTMLElementCollection* elementCollection = NULL;
doc_main->get_all(&elementCollection);
4 获得相应ID的IDispatch对象。
我理解IDispatch是其他对象的基类,是一个统一的标准接口。
以下代码,获取id为“btn_OK”的IDispatch对象。
IDispatch* spDisp = NULL;
elementCollection->item(CComVariant("btn_OK"), CComVariant("0"), &spDisp);
5 转换IDispatch对象为IHTMLFormElement对象。
我理解是把IDispatch对象转换到具体的对象,然后由具体的对象进行操作。
IHTMLFormElement* pIHTMLFormElement = NULL;
spDisp->QueryInterface(IID_IHTMLFormElement,(void**)&pIHTMLFormElement);
if(pIHTMLFormElement) pIHTMLFormElement->submit(); //获得后,提交表单
6 转换IDispatch对象为IHTMLElement对象。
IHTMLElement和IHTMLElement2是IE浏览器(WebBrowser控件,trident内核)的两个同系列针对文档元素的接口。这两个接口都提供了以编程方式访问常见的所有元素对象的属性和方法的途径。
IHTMLElement* ssHtmlElement = NULL;
spDisp->QueryInterface(IID_IHTMLElement,(void**)&ssHtmlElement);
if(ssHtmlElement)ssHtmlElement->click(); //使用点击操作
按道理,以上两种都可以实现点击提交表单。但是有时候使用IHTMLElement更有效。
不是很理解原因,暂记录。