如何实现对Frame中HTML源码的直接读写
CMyView(派生于CHtmlView)的成员函数SetHtml的作用是在框架lpszTargetFrameName中显示lpszHtml所代表的Web内容(lpszHtml就是HTML源码),当lpszTargetFrameName为空时则直接显示在CMyView所在的页面中。程序运行时对非Frame可以正常工作,可对Frame却检取不到文档对象的IPersistStreamInit接口.
要求:
实现对Frame中HTML源码的直接读写(不能借助于临时文件);
给出例程
对最早给出可行方案的至少给予200分,其他人酌情给分。
如分数不够可以再加。
下面是SetHtml程序的实现
BOOL CMyView::SetHtml(LPCTSTR lpszHtml, LPCTSTR lpszTargetFrameName)
{
LPSTREAM pStream=NULL;
HGLOBAL hHTMLText=NULL;
IPersistStreamInit *psi=NULL;
LPDISPATCH pDisp=GetHtmlDocument( );
if (pDisp==NULL) return FALSE;
IHTMLDocument2 *pDoc=NULL;
HRESULT hr=pDisp->QueryInterface(IID_IHTMLDocument2,(void**)&pDoc);
pDisp->Release();
if (hr!=S_OK) return FALSE;
if (lpszTargetFrameName&&_tcslen(lpszTargetFrameName)>0)
{
IHTMLFramesCollection2 *pFrames=NULL;
hr=pDoc->get_frames(&pFrames);
pDoc->Release();
pDoc=NULL;
if (hr==S_OK)
{
COleVariant varIndex(lpszTargetFrameName),varResult;
hr=pFrames->item(&varIndex, &varResult);
pFrames->Release();
pDisp=varResult.pdispVal;
if (hr==S_OK&&pDisp!=NULL)
{
IHTMLWindow2 *pWin = NULL;
hr=pDisp->QueryInterface(IID_IHTMLWindow2,(void**)&pWin);
pDisp->Release();
if (hr==S_OK)
{
hr=pWin->get_document(&pDoc);
pWin->Release();
if (hr!=S_OK) return FALSE;
}
}
}
}
try
{
//一面这行对于Frame总是查询不到IPersistStreamInit接口
if (pDoc->QueryInterface(IID_IPersistStreamInit, (void**)&psi)!=S_OK) throw 1;
if (psi->InitNew()!=S_OK) throw 2;
int len=_tcslen(lpszHtml)+1;
hHTMLText=GlobalAlloc(GPTR,len*sizeof(TCHAR));
if (hHTMLText==NULL) throw 3;
_tcscpy((LPTSTR)hHTMLText,lpszHtml);
if (CreateStreamOnHGlobal(hHTMLText, true, &pStream)!=S_OK) throw 4;
if (psi->Load(pStream)!=S_OK) throw 5;
return TRUE;
}
catch(int e)
{
switch(e)
{
case 5:
pStream->Release();
case 4:
GlobalFree(hHTMLText);
case 3:
case 2:
psi->Release();
case 1:
pDoc->Release();
break;
}
return FALSE;
}
}