(1)新建一个MFC对话框项目
(2)对话框中添加WebBrower控件,添加方法:点击菜单栏工具->选择工具箱项->在弹出的选择工具箱项对话框选择COM组件->Microsoft Web Browser->确定,添加到对话框中即可。
(3)将CWebBrowser2.h和CWebBrowser2.cpp添加到项目中,XXXdlg.h中包含头文件
#include "CWebbrowser2.h",定义变量CWebBrowser2 m_web;
(4)XXXdlg.cpp的DoDataExchange中添加将控件与变量动态绑定
DDX_Control(pDX, IDC_EXPLORER1, m_web);
(5)XXXdlg.cpp的初始化函数中添加
VARIANT vt;
COleVariant vaUrl=_T("http://www.baidu.com");
m_web.Navigate2(vaUrl,&vt,&vt,&vt,&vt);
运行程序,可以看到自动加载百度页面。
(6)XXXdlg.h中添加一下声明,用于当页面加载完成后进一步操作页面
DECLARE_EVENTSINK_MAP()
void DocumentCompleteExplorer(LPDISPATCH pDisp, VARIANT* URL);
(7)XXXdlg.cpp中添加
BEGIN_EVENTSINK_MAP(CbaiduDlg, CDialogEx)
ON_EVENT(CbaiduDlg, IDC_EXPLORER1, 259, CbaiduDlg::DocumentCompleteExplorer, VTS_DISPATCH VTS_PVARIANT)
END_EVENTSINK_MAP()
(8)实现DocumentCompleteExplorer
分析百度源码可以得到输入框的id是kw1,按钮的id是su1。
<span style="font-size:18px;">void CbaiduDlg::DocumentCompleteExplorer(LPDISPATCH pDisp, VARIANT* URL) { HRESULT hr; LPUNKNOWN lpUnknown; LPUNKNOWN lpUnknownWB = NULL; LPUNKNOWN lpUnknownDC = NULL; IHTMLElementCollection *objAllElement=NULL; IHTMLDocument2 *objDocument=NULL; CString strUrl,strTemp; lpUnknown = m_web.GetControlUnknown(); ASSERT(lpUnknown); if (lpUnknown) { hr = lpUnknown->QueryInterface(IID_IUnknown,(LPVOID*)&lpUnknownWB); ASSERT(SUCCEEDED(hr)); if (FAILED(hr)) return; hr = pDisp->QueryInterface(IID_IUnknown, (LPVOID*)&lpUnknownDC); ASSERT(SUCCEEDED(hr)); if (SUCCEEDED(hr) && lpUnknownWB == lpUnknownDC) { // The document has finished loading. strUrl=m_web.get_LocationURL(); if (strUrl.IsEmpty()) { return ; } objDocument=(IHTMLDocument2*)m_web.get_Document(); objDocument->get_all(&objAllElement); if (strUrl==_T("http://www.baidu.com/")) { CComPtr<IDispatch>pDisp; objAllElement->item(COleVariant(_T("kw1")),COleVariant((long)0),&pDisp); CComQIPtr<IHTMLElement, &IID_IHTMLElement>pElement; if(pDisp==NULL) { return; } else { pElement=pDisp; pElement->put_innerText(_T("测试")); //填充表单 } VARIANT name; CComBSTR tag; long index; objAllElement-> get_length(&index); name.vt=VT_I4; for(long i=0; i <index; i++)//遍历所有元素,通过id属性获取值 { name.lVal = i; IDispatch * pDispatch=NULL; objAllElement-> item(name,name,&pDispatch); IHTMLElement* spElement; pDispatch-> QueryInterface(IID_IHTMLElement, (void**)&spElement); BSTR tag; spElement->get_id(&tag); CString ss(tag); if(ss == "su1") spElement->click(); spElement->Release(); } } } } if (lpUnknownWB) lpUnknownWB->Release(); if (lpUnknownDC) lpUnknownDC->Release(); }</span>
运行可以看到百度自动搜索