Skip to main content Skip to navigation

Open new tab in explorer using C++

I wanted to write a program that would output results to a web page in Internet Explorer, reusing any existing instance of Explorer otherwise creating a new instance. Any other web browser types should be ignored.

There were not any code samples that did what I wanted, so after much trial and error I produced some working code. The following method will output the contents of the file at the location path to Internet Explorer.

First of all, create an instance of IShellWindows and count how many File and Web explorer windows we have

void OutputToWebBrowser(const CString & path)
{
IShellWindows *psw;
HRESULT hr = CoCreateInstance(CLSID_ShellWindows,NULL,CLSCTX_ALL,IID_IShellWindows,(void**)&psw);
if (!SUCCEEDED(hr)) return;
IWebBrowser2* pBrowser2 = 0;
bool found = false;
long nCount = 0;
hr = psw->get_Count(&nCount);
if (SUCCEEDED(hr))
{

And then iterate through them finding one that is a WebBrowser and has IEXPLORE in the pathname, ie is not another web browser

    for (long i = nCount - 1; (i >= 0) && (!found); i--) {
// get interface to item no i
_variant_t va(i, VT_I4);
IDispatch * spDisp;
hr = psw->Item(va,&spDisp);
hr = spDisp->QueryInterface(IID_IWebBrowserApp,(void **)&pBrowser2);
if (SUCCEEDED(hr))
{
BSTR name;
pBrowser2->get_FullName(&name);
CString n(name);
if (n.Find("IEXPLORE") == -1)
pBrowser2->Release();
else
found = true;
}
}
psw->Release();
}

If we did not find an instance of a web browser then make one

if (!found)
hr = CoCreateInstance(CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER,
IID_IWebBrowser2, (void**)&pBrowser2);

And then use the instance that we found, or created, to output the web page

if (SUCCEEDED(hr))
{
VARIANT vEmpty;
VariantInit(&vEmpty);
_variant_t URL, Flag, TargetFrameName, PostData, Headers;
Flag.ChangeType(VT_I4, &Flag);
if (found)
Flag.intVal = 0x800;
URL.SetString(path);

hr = pBrowser2->Navigate2(&URL, &Flag, &vEmpty, &vEmpty, &vEmpty);
if (SUCCEEDED(hr))
{
pBrowser2->put_Visible(TRUE);
}
else
{
pBrowser2->Quit();
}
pBrowser2->Release();
}
}