使用案例:有人要我自动化他的网络浏览器。每天,他必须导航到相同的URL,输入相同的凭据并登录。他希望计算机自动执行此操作:使用导航到URL的应用程序,输入发布数据并自动登录。然后,他可以继续手动浏览页面。
因此,如果我想直接控制现有的Internet Explorer实例,我将如何使用C ++实现?
答案 0 :(得分:1)
经过数小时的研究,我设法打开IE的新实例并导航到特定的URL。
我采取的步骤:
在项目选项中链接以下库:libole32.a,liboleaut32.a,liboleacc.a,libuuid.a
在主cpp文件的开头包含cassert和exdisp.h。
在主cpp文件中插入以下代码:
int main(void) {
HRESULT hret;
hret=CoInitialize(NULL);
assert(SUCCEEDED(hret));
CLSID clsid; // Get IE CLSID
hret=CLSIDFromProgID(L"InternetExplorer.Application",&clsid);
assert(SUCCEEDED(hret));
IUnknown *p; // Get IUnknown Interface
hret=CoCreateInstance(clsid,NULL,CLSCTX_ALL,IID_IUnknown,reinterpret_cast<void**>(&p));
assert(SUCCEEDED(hret));
IDispatch *q; // Get IDispatch Interface from IUnknown
hret=p->QueryInterface(IID_IDispatch,reinterpret_cast<void**>(&q));
assert(SUCCEEDED(hret));
IWebBrowser2 *r; // Get IWebBrowser2 Interface from IDispatch
hret=q->QueryInterface(IID_IWebBrowser2,reinterpret_cast<void**>(&r));
assert(SUCCEEDED(hret));
IUnknown *s; // Get IUnknown from IWebBrowser2
hret=r->QueryInterface(IID_IUnknown,reinterpret_cast<void**>(&s));
assert(SUCCEEDED(hret));
///// Transitive //////////////////////////
assert(p==s);
////////////////////////////////////////
VARIANT vEmpty;
VariantInit(&vEmpty);
VARIANT vFlags;
V_VT(&vFlags) = VT_I4;
V_I4(&vFlags) = navOpenInNewWindow;
BSTR bstrURL = SysAllocString(L"http://www.google.com");
r->Navigate(bstrURL, &vFlags, &vEmpty, &vEmpty, &vEmpty);
r->Quit();
SysFreeString(bstrURL);
p->Release(); q->Release(); r->Release(); s->Release();
CoUninitialize(); return 0;
}
HRESULT hret;
hret=CoInitialize(NULL);
assert(SUCCEEDED(hret));
CLSID clsid; // Get IE CLSID
hret=CLSIDFromProgID(L"InternetExplorer.Application",&clsid);
assert(SUCCEEDED(hret));
IUnknown *p; // Get IUnknown Interface
hret=CoCreateInstance(clsid,NULL,CLSCTX_ALL,IID_IUnknown,reinterpret_cast<void**>(&p));
assert(SUCCEEDED(hret));
IDispatch *q; // Get IDispatch Interface from IUnknown
hret=p->QueryInterface(IID_IDispatch,reinterpret_cast<void**>(&q));
assert(SUCCEEDED(hret));
IWebBrowser2 *r; // Get IWebBrowser2 Interface from IDispatch
hret=q->QueryInterface(IID_IWebBrowser2,reinterpret_cast<void**>(&r));
assert(SUCCEEDED(hret));
IUnknown *s; // Get IUnknown from IWebBrowser2
hret=r->QueryInterface(IID_IUnknown,reinterpret_cast<void**>(&s));
assert(SUCCEEDED(hret));
///// Transitive //////////////////////////
assert(p==s);
////////////////////////////////////////
VARIANT vEmpty;
VariantInit(&vEmpty);
VARIANT vFlags;
V_VT(&vFlags) = VT_I4;
V_I4(&vFlags) = navOpenInNewWindow;
BSTR bstrURL = SysAllocString(L"http://www.google.com");
r->Navigate(bstrURL, &vFlags, &vEmpty, &vEmpty, &vEmpty);
r->Quit();
SysFreeString(bstrURL);
p->Release(); q->Release(); r->Release(); s->Release();
CoUninitialize(); return 0;
}