用com操作word

本文介绍了一种使用COM技术直接调用Word应用程序对象接口的方法,通过示例代码展示了创建、操作和保存Word文档的过程。讨论了程序完成后Office应用程序仍驻留内存的问题,指出可能是由于忘记释放接口导致的引用计数错误。解决方案包括检查并正确释放IDispatch指针,以及在不再需要时调用Quit方法退出应用程序。
摘要由CSDN通过智能技术生成

使用com技术对word进行操作,不同于网上流行的使用类型库的方法,直接调用word应用程序对象的接口方法,

以下是一个简单应用的代码:

int main(int argc, char* argv[])
{

    // ******************* Declare Some Variables ********************

    // Variables that will be used and re-used in our calls
    DISPPARAMS dpNoArgs = {NULL, NULL, 0, 0};
    VARIANT vResult;
    OLECHAR FAR* szFunction;
    BSTR bstrTemp;

    // IDispatch pointers for Word's objects
    IDispatch* pDispDocs;      //Documents collection
    IDispatch* pDispSel;       //Selection object
    IDispatch* pDispActiveDoc; //ActiveDocument object

    // DISPID's
    DISPID dispid_Docs;        //Documents property of Application object
    DISPID dispid_DocsAdd;     //Add method of Documents collection
                               //object
    DISPID dispid_Sel;         //Selection property of Applicaiton object
    DISPID dispid_TypeText;    //TypeText method of Selection object
    DISPID dispid_TypePara;    //TypeParagraph method of Selection object
    DISPID dispid_ActiveDoc;   //ActiveDocument property of Application
                               //obj
    DISPID dispid_SaveAs;      //SaveAs method of the Document object
    DISPID dispid_Quit;        //Quit method of the Application object

    // ******************** Start Automation ***********************

    //Initialize the COM libraries
    ::CoInitialize(NULL);

    // Create an instance of the Word application and obtain the pointer
    // to the application's IDispatch interface.
    CLSID clsid;
    CLSIDFromProgID(L"Word.Application", &clsid); 

    IUnknown* pUnk;
    HRESULT hr = ::CoCreateInstance( clsid, NULL, CLSCTX_SERVER,
                                     IID_IUnknown, (void**) &pUnk);
    IDispatch* pDispApp;
    hr = pUnk->QueryInterface(IID_IDispatch, (void**)&pDispApp);

    // Get IDispatch* for the Documents collection object
    szFunction = OLESTR("Documents");
    hr = pDispApp->GetIDsOfNames (IID_NULL, &szFunction, 1,
                                  LOCALE_USER_DEFAULT, &dispid_Docs);
    hr = pDispApp->Invoke (dispid_Docs, IID_NULL, LOCALE_USER_DEFAULT,
                           DISPATCH_PROPERTYGET, &dpNoArgs, &vResult,
                           NULL, NULL);
    pDispDocs = vResult.pdispVal;

    // Invoke the Add method on the Documents collection object
    // to create a new document in Word
    // Note that the A

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值