DocumentComplete event in Embedded IWebBrowser2 using write() method

一笑奈何 提交于 2019-12-05 14:38:06

Thanks to Remy, I tried again loading with IPersistStreamInit and now it seems to be working. Here it is the new displayHTMLStr():

HRESULT STDMETHODCALLTYPE EmbBrowser::displayHTMLStr(LPCTSTR htmlSource) {
  HRESULT                   hr;

  IDispatch                 *pDispatch = 0;
  IHTMLDocument2            *pHtmlDoc2 = 0;
  IPersistStreamInit        *pPSI = 0;
  IStream                   *pStream = 0;
  HGLOBAL                   hHTMLContent;

  hr = m_webBrowser->get_Document(&pDispatch);
  if (FAILED(hr) || !pDispatch) {
    goto displayHTMLStr_clean;
  }

  hr = pDispatch->QueryInterface(IID_IHTMLDocument2, (void **) &pHtmlDoc2);
  if (FAILED(hr) || !pHtmlDoc2) {
    goto displayHTMLStr_clean;
  }

  hr = pHtmlDoc2->QueryInterface(IID_IPersistStreamInit, (void **) &pPSI);
  if (FAILED(hr) || !pPSI) {
    goto displayHTMLStr_clean;
  }

  // allocate global memory to copy the HTML content to
  hHTMLContent = ::GlobalAlloc(GPTR, (::_tcslen(htmlSource) + 1) * sizeof(TCHAR));
  if (!hHTMLContent) {
    hr = E_OUTOFMEMORY;
    goto displayHTMLStr_clean;
  }

  ::_tcscpy((TCHAR *) hHTMLContent, htmlSource);

  // create a stream object based on the HTML content
  hr = ::CreateStreamOnHGlobal(hHTMLContent, TRUE, &pStream);
  if (FAILED(hr) || !pStream) {
    goto displayHTMLStr_clean;
  }

  hr = pPSI->InitNew();
  if (FAILED(hr)) {
    goto displayHTMLStr_clean;
  }

  // Connect HTMLDocumentEvents2 to get onDocumentComplete and onClick events
  this->connectEvents();
  hr = pPSI->Load(pStream);

  _tprintf(_T("Written: \n%s\n\n"), htmlSource);


displayHTMLStr_clean:

  if (pStream) {
    pStream->Release();
  }
  if (hHTMLContent) {
    GlobalFree(hHTMLContent);
  }
  if (pPSI) {
    pPSI->Release();
  }
  if (pHtmlDoc2) {
    pHtmlDoc2->Release();
  }
  if (pDispatch) {
    pDispatch->Release();
  }

  return hr;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!