以下是在OLE自动化的后台运行Ms Word的代码:
int _tmain(int argc, _TCHAR* argv[])
{
CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
CLSID clsid;
HRESULT hr = CLSIDFromProgID(L"Word.Application", &clsid);
IDispatch *pWApp;
if(SUCCEEDED(hr))
{
//here the process starts
hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER,
IID_IDispatch, (void **)&pWApp);
cout << "success" << endl;
}
//here I try to end it
pWApp->Release();
CoUninitialize();
return 0;
}
不幸的是,在我的程序结束后,Word仍然在内存中。怎么阻止它?
答案 0 :(得分:2)
您正在创建的Word.Application
对象有一个Quit()
方法,您可以选择在Release()
指向对象的接口指针之前调用该方法:
退出Microsoft Word并选择保存或路由打开的文档。
由于您拥有对象的IDispatch
界面,因此您可以使用IDispatch::GetIDsOfNames()
和IDispatch::Invoke()
方法调用Word.Application.Quit()
方法,例如:
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
if (SUCCEEDED(hr))
{
CLSID clsid;
hr = CLSIDFromProgID(L"Word.Application", &clsid);
if (SUCCEEDED(hr))
{
IDispatch *pWApp;
hr = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IDispatch, (void **)&pWApp);
if (SUCCEEDED(hr))
{
cout << "success" << endl;
// use pWApp as needed ...
DISPID dispID;
LPOLESTR ptName = L"Quit"; //name of the method
hr = pWApp->GetIDsOfNames(IID_NULL, &ptName, 1, LOCALE_USER_DEFAULT, &dispID);
if (SUCCEEDED(hr))
{
//no parameters
DISPPARAMS dp = {NULL, NULL, 0, 0};
hr = pWApp->Invoke(dispID, IID_NULL, LOCALE_SYSTEM_DEFAULT, DISPATCH_METHOD, &dp, NULL, NULL, NULL);
}
pWApp->Release();
}
}
CoUninitialize();
}
return 0;
}