调用的参数书写都正确,可是每次调用pElem都返回空指针?
CComPtr<IDispatch> pDisp = (IDispatch*)GetDocument();
CComPtr<IHTMLDocument3> pDoc;
HRESULT hr = pDisp->QueryInterface(IID_IHTMLDocument3, (void**)&pDoc);
if (SUCCEEDED(hr))
{
hr = pDoc->getElementById(CComBSTR(szId), pElem);
CComPtr<IHTMLDocument3> pDoc;
HRESULT hr = pDisp->QueryInterface(IID_IHTMLDocument3, (void**)&pDoc);
if (SUCCEEDED(hr))
{
hr = pDoc->getElementById(CComBSTR(szId), pElem);
}
原因:文档还没有加载完毕,需要等到文档加载完毕后再调用getElementById方法。
解决方法:调用以下函数等待文档加载完毕
bool WaitTillLoaded (int nTimeout)//毫秒数
{
READYSTATE result;
DWORD nFirstTick = GetTickCount ();
do
{
m_pWebBrowser->get_ReadyState (&result);
if (result != READYSTATE_COMPLETE)
Sleep (250);
if (nTimeout > 0)
{
if ((GetTickCount () - nFirstTick) > nTimeout)
break;
}
} while (result != READYSTATE_COMPLETE);
if (result == READYSTATE_COMPLETE)
return true;
else
return false;
}
{
READYSTATE result;
DWORD nFirstTick = GetTickCount ();
do
{
m_pWebBrowser->get_ReadyState (&result);
if (result != READYSTATE_COMPLETE)
Sleep (250);
if (nTimeout > 0)
{
if ((GetTickCount () - nFirstTick) > nTimeout)
break;
}
} while (result != READYSTATE_COMPLETE);
if (result == READYSTATE_COMPLETE)
return true;
else
return false;
}