请高手帮忙解决一个OLE的问题
现有个需求:用程序读取数据生成WORD文档,并把文档显示到程序窗口中,但要防止文档内容被保存。通过查询网上的文章,我已经掌握通过OLE技术可以实现把WORD文档显示到窗口的方法,该方法就是创建一个COleClientItem实例,调用该实例的CreateFromFile()函数创建一个embeded item,然后调用该实例的DoVerb()函数把文档显示到窗口。但这个方法不满足我的需求:我的WORD文档是程序生成的,并且不能写入到磁盘中,不能调用CreateFromFile()函数来创建embeded item。我发现COleClientItem类还有一个CreateFromData()函数,但尝试了一些方法用该函数生产embeded Item,但始终不成功,我的代码如下:extern "C"
{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
UINT32 GetFileLength(FILE * fp)
{
UINT32 ulFileLength = 0;
if(NULL == fp)
{
return 0;
}
fseek(fp, 0, SEEK_END);
ulFileLength = ftell(fp);
fseek(fp, 0, SEEK_SET);
return ulFileLength;
}
HGLOBAL CreateFileHandle(char *filename)
{
FILE *fp;
UINT8 *buf = NULL;
fp = fopen(filename, "rb");
int flen = GetFileLength(fp);
buf = (UINT8 *)malloc(flen);
if(NULL == buf)
{
return NULL;
}
fread(buf, 1, flen, fp);
fclose(fp);
HGLOBAL hmem = ::GlobalAlloc(GMEM_MOVEABLE, flen);
byte *pdib = (byte*)::GlobalLock(hmem);
memcpy(pdib, buf, flen);
::GlobalUnlock(hmem);
free(buf);
return pdib;
}
} //extern "C"
void CEmbed_WordView::EmbedAutomateWord()
{
BeginWaitCursor();
CEmbed_WordCntrItem* pItem = NULL;
TRY
{
CEmbed_WordDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
pItem = new CEmbed_WordCntrItem(pDoc);
ASSERT_VALID(pItem);
CLSID clsid;
if (FAILED(::CLSIDFromProgID(L"Word.document", &clsid)))
{
AfxThrowMemoryException();
}
/*
if (!pItem->CreateFromFile(m_sPath, clsid))
{
AfxThrowMemoryException();
}
*/
char fileName[256];
int i, len = m_sPath.GetLength();
for(i=0; i<len; i++)
{
fileName[i] = m_sPath[i];
}
fileName[i] = '\0';
//仅用于测试方法是否可行,所以这里WORD文件还是从磁盘读取的,而未用程序生成
//这段代码仅用于测试用COleClientItem::CreateFromData()来生成embeded Item是否可行
HANDLE hdl = CreateFileHandle(fileName);
COleDataSource src;
src.CacheGlobalData(CF_TEXT, hdl, NULL);
LPDATAOBJECT lpDataObj = (LPDATAOBJECT)src.GetInterface(&IID_IDataObject);
COleDataObject obj;
obj.Attach(lpDataObj, FALSE);
pItem->CreateFromData(&obj, OLERENDER_DRAW, CF_TEXT, NULL);
pItem->DoVerb(OLEIVERB_SHOW, this);
m_pSelection = pItem;
pDoc->UpdateAllViews(NULL);
LPDISPATCH lpDisp;
lpDisp = pItem->GetIDispatch();
}
CATCH(CException, e)
{
if (pItem != NULL)
{
ASSERT_VALID(pItem);
pItem->Delete();
}
AfxMessageBox(IDP_FAILED_TO_CREATE);
}
END_CATCH
EndWaitCursor();
}
请大侠赐教,感谢!
[ 本帖最后由 camford 于 2014-1-18 12:08 编辑 ]