mshtml的一个问题。我如果才能获得往head部分写一行html
我获得了head的IHTMLElementCollection,问题是我下一步该怎么从IHTMLElementCollection里正确的获取一个IHTMLElement呢?大家多多帮忙。
代码如下:
CString strPos = "BeforeBegin";
IHTMLElement *pElement= NULL;
IHTMLDocument2 *pDoc;
if(SUCCEEDED(HrGetDoc(&pDoc))) //获取IHTMLDocument2
{
IHTMLElementCollection *pElementCollection;
if(SUCCEEDED(pDoc->get_all(&pElementCollection)))
{
CString strname = "head";
VARIANT name,index;
VariantInit(&name);
VariantInit(&index);
V_VT(&name) = VT_BSTR ;
V_BSTR(&name) = strname.AllocSysString();
IHTMLElementCollection *pdisp;
if((pElementCollection->tags(name,(IDispatch**)&pdisp)) == S_OK)//获取head的IHTMLElementCollection
{
long len;
pdisp->get_length(&len);//运行到此处len为1
for(int i = 0;i<len;i++)
{
COleVariant varIndex,var2;
varIndex.vt=VT_UINT;
varIndex.lVal=i;
IHTMLElement *pElement;
if(pdisp->item(varIndex,var2,(IDispatch**)&pElement) == S_OK)
{
CString strScript = " <style type=text/css><!--p{margin-top: 0; margin-bottom: 0;}--></style>";
BSTR bstrPos = strPos.AllocSysString();
BSTR bstrContent = strScript.AllocSysString();
pElement->insertAdjacentHTML( bstrPos, bstrContent );//pElement不为空,但是出现非法操作,这里该怎么办呢?
::SysFreeString(bstrPos);
::SysFreeString(bstrContent);
pElement->Release();
}
}
pdisp->Release();
}
VariantClear(&name);
pElementCollection->Release();
}
pDoc->Release();
}