我是 MFC 的新手。我正在使用 OLEInitialize() 来初始化 COM 对象,使用 COCreateInstance() 来创建对象的实例 (EXCEL.EXE),并使用 OLEUnInitialize() 来取消初始化 com 对象。但在 Windows XP 中,调用 OLEUnInitialize() 后,EXCEL.EXE 结束。但在 Windows 7 中却没有。如果你们有任何想法,请帮助我。提前致谢。
这是构造函数:
CXLAutomation::CXLAutomation(BOOL bVisible)
{
m_pdispExcelApp = NULL;
m_pdispWorkbook = NULL;
m_pdispWorksheet = NULL;
m_pdispActiveChart = NULL;
InitOLE();
StartExcel();
SetExcelVisible(bVisible);
CreateWorkSheet();
}
析构函数:
CXLAutomation::~CXLAutomation()
{
ReleaseDispatch();
OleUninitialize();
}
功能:
BOOL CXLAutomation::InitOLE()
{
DWORD dwOleVer;
dwOleVer = CoBuildVersion();
// check the OLE library version
if (rmm != HIWORD(dwOleVer))
{
MessageBox(NULL, L"Incorrect version of OLE libraries.", L"Failed", MB_OK | MB_ICONSTOP);
return FALSE;
}
// could also check for minor version, but this application is
// not sensitive to the minor version of OLE
// initialize OLE, fail application if we can't get OLE to init.
if (FAILED(OleInitialize(NULL)))
{
MessageBox(NULL, L"Cannot initialize OLE.", L"Failed", MB_OK | MB_ICONSTOP);
return FALSE;
}
return TRUE;
}
BOOL CXLAutomation::StartExcel()
{
CLSID clsExcelApp;
// if Excel is already running, return with current instance
if (m_pdispExcelApp != NULL)
return TRUE;
/* Obtain the CLSID that identifies EXCEL.APPLICATION
* This value is universally unique to Excel versions 5 and up, and
* is used by OLE to identify which server to start. We are obtaining
* the CLSID from the ProgID.
*/
if (FAILED(CLSIDFromProgID(L"Excel.Application", &clsExcelApp)))
{
MessageBox(NULL, L"Cannot obtain CLSID from ProgID", L"Failed", MB_OK | MB_ICONSTOP);
return FALSE;
}
// start a new copy of Excel, grab the IDispatch interface
if (FAILED(CoCreateInstance(clsExcelApp, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void**)&m_pdispExcelApp)))
{
MessageBox(NULL, L"Cannot start an instance of Excel for Automation.", L"Failed", MB_OK | MB_ICONSTOP);
return FALSE;
}
return TRUE;
}