(1)使用appwizard创建一个新的mfc appwizard(exe)工程,命名为"office"
(2)选择单文档视图(sdi)结构,在第3步中需要选中container,以提供容器支持,并且选中active document container 其它都为默认
(3)在view菜单中,选classwizard,选automation选项卡,选add class,选择from a typelibrary, 在office目录中选中microsoft word 97/2000 类型库word8.olb或word9.olb,选中application,document,_document。单击ok
(4)给cofficecntritem添加一方法。getidispatch()
其源码如下:
assert_valid(this);
assert(m_lpobject != null);
lpunknown lpunk = m_lpobject;
run();
lpolelink lpolelink = null;
if (m_lpobject->queryinterface(iid_iolelink, (lpvoid far*)&lpolelink) == noerror)
{
assert(lpolelink != null);
lpunk = null;
if (lpolelink->getboundsource(&lpunk) != noerror)
{
trace0("warning: link is not connected!\n");
lpolelink->release();
return null;
}
assert(lpunk != null);
}
lpdispatch lpdispatch = null;
if (lpunk->queryinterface(iid_idispatch, (lpvoid far*)&lpdispatch)!=noerror)
{
trace0("warning: does not support idispatch!\n");
return null;
}
assert(lpdispatch != null);
return lpdispatch;
(5)。在officeview.h添加#include "msword8.h"
(6)。修改void cofficeview::oninsertobject(),源码如下:
beginwaitcursor();
cofficecntritem* pitem = null;
try
{
// create new item connected to this document.
cofficedoc* pdoc = getdocument();
assert_valid(pdoc);
pitem = new cofficecntritem(pdoc);
assert_valid(pitem);
// initialize the item from the dialog data.
/* if (!dlg.createitem(pitem))
afxthrowmemoryexception(); // any exception will do
assert_valid(pitem);*/
clsid clsid; //
if(failed(::clsidfromprogid(l"word.document",&clsid)))
afxthrowmemoryexception();
if(!pitem->createnewitem(clsid))
/*if(!pitem->createfromfile (filename,clsid)) */
afxthrowmemoryexception();
assert_valid(pitem);
pitem->activate (oleiverb_show,this);
assert_valid(pitem);
m_pselection = pitem; // set selection to last inserted item
pdoc->updateallviews(null);
// as an arbitrary user interface design, this sets the selection
// to the last item inserted.
// todo: reimplement selection as appropriate for your application
m_pselection = pitem; // set selection to last inserted item
pdoc->updateallviews(null);
}
catch(cexception, e)
{
if (pitem != null)
{
assert_valid(pitem);
pitem->delete();
}
afxmessagebox(idp_failed_to_create);
}
end_catch
endwaitcursor();
(7)重载id—file—save,
void cofficeview::onfilesave()
{
// todo: add your command handler code here
try{
lpdispatch lpdisp;
lpdisp = m_pselection->getidispatch();
documents docs;
_application app;
_document mydoc;
documents my;
mydoc.attachdispatch (lpdisp,true);
app=mydoc.getapplication ();
/* app.run ("macro3");*/
mydoc.activate ();
bool password=mydoc.gethaspassword ();
mydoc.setpassword ("love");
password=mydoc.gethaspassword ();
colevariant vfalse((short)false);
mydoc.saveas (colevariant("c:\\love.doc"),vfalse,vfalse, colevariant(""),vfalse,
colevariant(""),vfalse,vfalse,vfalse,vfalse,vfalse);
}
catch(cexception, e)
{
}