简体   繁体   English

IWebBrowser2.Document不返回IHTMLDocument2

[英]IWebBrowser2.Document not returning IHTMLDocument2

I am trying to cast an IWebBrowser2 COM object into a IHTMLDocument2 so that I can manipulate the contents of the IE web browser. 我正在尝试将IWebBrowser2 COM对象转换为IHTMLDocument2,以便可以操纵IE Web浏览器的内容。

Here is the start of my code: 这是我的代码的开始:

int main()
{
    if (SUCCEEDED(OleInitialize(NULL)))
    {
        CComQIPtr<IWebBrowser2> pBrowser2;
        CComQIPtr<IDispatch> pDispatch;

        CoCreateInstance(CLSID_InternetExplorer, NULL, CLSCTX_LOCAL_SERVER,
            IID_IWebBrowser2, (void**)&pBrowser2);
        if (pBrowser2)
        {    
            //Here, pDispatch remains null and hr == E_FAIL
            HRESULT hr = pBrowser2->get_Document(&pDispatch);
        }
        OleUninitialize();
    }    
}

At the call to IWebBrowser2::get_Document() the pDispatch variable remains null and the returned HRESULT is E_FAIL. 在调用IWebBrowser2 :: get_Document()时,pDispatch变量保持为空,并且返回的HRESULT为E_FAIL。

What do I need to do to get the IHTMLDocument2 object from the IWebBrowser2? 我需要怎么做才能从IWebBrowser2获取IHTMLDocument2对象?

Call Navigate to open a webpage first. 呼叫Navigate先打开一个网页。 Otherwise there is no document to get. 否则,没有文件要获取。

if (pBrowser2)
{
    VARIANT vEmpty;
    VariantInit(&vEmpty);

    BSTR str = SysAllocString(L"http://google.com");
    HRESULT hr = pBrowser2->Navigate(str , &vEmpty, &vEmpty, &vEmpty, &vEmpty);
    if (SUCCEEDED(hr))
    {
        //optional: show the explorer window
        //pBrowser2->put_Visible(VARIANT_TRUE);

        hr = pBrowser2->get_Document(&pDispatch);
        if (hr == S_OK)
            OutputDebugStringW(L"okay\n");
    }

    SysFreeString(str);
    pBrowser2->Quit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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