简体   繁体   中英

How to get an Instance of IWebBrowser2

I am a bit new to C++, please be gentle.

I am trying to automate Internet Explorer. I have a simple Win32 console application where I am trying to create an instance of IE using a local server.

However, my call to CoCreateInstance() doesn't return an object to initialize my IWebBrowser2 variable.

I could use some help to see what I am missing.

Here is my code:

HRESULT InstanciateIEResult;
HRESULT NavigateResult;
HRESULT ShowBrowserResult;

VARIANT * empty = new VARIANT();

BSTR URL = L"bing.com";
IWebBrowser2*    pBrowser2;

InstanciateIEResult = CoCreateInstance(CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER,
    IID_IWebBrowser2, (void**)&pBrowser2);


if(pBrowser2)
{
    //never reach here
    NavigateResult = pBrowser2->Navigate(URL, empty, empty, empty, empty);
    ShowBrowserResult = pBrowser2->put_Visible(VARIANT_TRUE);
} 

I am also not sure how to decode what the HRESULT returns. If you know, that would be helpful as well.

I was looking at documentation on IWebBrowser2 interface and CoCreateInstance .

You need to call CoInitialize() before using COM objects.

Also, you need to use SysAllocString() to allocate the string.

Example:

#include <windows.h>
#include <MsHTML.h>
#include <Exdisp.h>
#include <ExDispid.h>

int WINAPI wWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
    CoInitialize(NULL);

    HRESULT InstanciateIEResult;
    HRESULT NavigateResult;
    HRESULT ShowBrowserResult;

    VARIANT empty;
    VariantInit(&empty);

    IWebBrowser2* browser = NULL;
    HRESULT hr = CoCreateInstance(CLSID_InternetExplorer, NULL,
            CLSCTX_LOCAL_SERVER, IID_IWebBrowser2, (void**)&browser);

    if (browser)
    {
        BSTR URL = SysAllocString(L"bing.com");
        NavigateResult = browser->Navigate(URL, &empty, &empty, &empty, &empty);
        SysFreeString(URL);

        ShowBrowserResult = browser->put_Visible(VARIANT_TRUE);
        browser->Release();
    }

    CoUninitialize();
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM