Reputation: 179
Use case: Someone asked me to automate his internet explorer. Every day, he has to navigate to the same URL, enter the same credentials und log in. He'd like the computer to do that automatically: With an application that navigates to the URL, enters the post data and logs in automatically. He then can continue to navigate manually through the page.
So, if I want to control directly an existing internet explorer instance, how would I do that with C++?
Upvotes: 1
Views: 978
Reputation: 179
After hours of research, I managed to open a new instance of the IE and navigating to a specific URL.
The steps I undertook:
Link the following libraries in the project options: libole32.a, liboleaut32.a, liboleacc.a, libuuid.a
Include cassert and exdisp.h at the beginning of the main cpp-file.
Insert the following code in the main cpp-file:
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;
}
Upvotes: 1