100分求分析DocumentComplete崩溃错误
我的一个CWebBrowser2控件
在DocumentComplete中,把html的内容动态的追加‘hello,world’在后面
但偶尔会程序崩溃,提示mshtml.dll出错。下面是代码,请熟悉com的朋友
帮我看看,哪里有指针或者资源方面的错误。
谢谢。
void CMyDemo::DocumentCompleteExplorer1(LPDISPATCH pDisp, VARIANT* URL)
{
if (pDisp == NULL) return;
if (URL->bstrVal == NULL) return;
CString strUrl = (CString)(*URL);
if (strUrl.Find(_T("http:")) < 0) return;
try
{
HRESULT hr;
// get IWebBrowser2
IWebBrowser2 * pWebBrowser = NULL;
hr = pDisp->QueryInterface(IID_IWebBrowser2,
(void **)&pWebBrowser);
if (FAILED(hr)) return;
if (pWebBrowser == NULL) return;
// get document
CComPtr<IDispatch> spDispDoc;
hr = pWebBrowser->get_Document(&spDispDoc);
if (FAILED(hr)) return;
if (spDispDoc == NULL) return;
CComPtr<IHTMLDocument2> spHTMLDoc;
hr = spDispDoc->QueryInterface(IID_IHTMLDocument2,(void**)&spHTMLDoc);
if (FAILED(hr)) return;
if (spHTMLDoc == NULL) return;
IHTMLDocument2* document = NULL;
document = spHTMLDoc;
CComPtr<IHTMLElement> body;
IHTMLElement *parent;
// get the body object
hr = document->get_body(&body);
if (FAILED(hr)) return;
// 通过body,取得html
hr = body->get_parentElement(&parent);
if (FAILED(hr)) return;
if (parent == NULL) return;
// get html
BSTR bstr;
CString str;
hr = parent->get_outerHTML(&bstr);
if (FAILED(hr)) return;
// body->get_outerHTML(&bstr);
str = bstr;
SAFEARRAY *safe_array = SafeArrayCreateVector(VT_VARIANT, 0, 1);
if (safe_array == NULL) return;
VARIANT *variant = NULL;
hr = SafeArrayAccessData(safe_array,(LPVOID *)&variant);
if (FAILED(hr))
return;
variant->vt = VT_BSTR;
// 追加 hello,world
str += _T("hello, world");
variant->bstrVal = CString(str).AllocSysString();
// write SAFEARRAY to browser document
document->write(safe_array);
document->close();
SafeArrayUnaccessData(safe_array);
// release
parent->Release();
pWebBrowser->Release();
}catch(...)
{
// NOOP
}
}