如何结束COM自动化过程中执行的进程

How to end the process executed during COM automation

以下是在后台运行 Ms Word 以实现 OLE 自动化的代码:

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 在我的程序结束后仍保留在内存中。如何停止?

您可以在 Release() 指向对象的接口指针之前选择性调用的 Word.Application object that you are creating has a Quit() 方法:

Quits Microsoft Word and optionally saves or routes the open documents.

因为你有一个IDispatch interface to the object, you can use the IDispatch::GetIDsOfNames() and 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;
}