c++ 如何使用Ole自动化获取活动Word文档的完整路径

zaq34kh6  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(131)

我已经成功地获得了使用Ole自动化当前活动的Word文档的文件名。顺便问一下,我如何获得此文档的完整文件路径?
从下面的代码中,我只得到当前在fileName中打开的文档的名称,但我想知道完整的文件路径。我该怎么办?

CLSID clsid;
IDispatch* wordApp = NULL;
COleDispatchDriver driver;

CoInitialize(NULL);
HRESULT m_hr = CLSIDFromProgID(L"Word.Application", &clsid);
if (FAILED(m_hr))
{
    return false;
}

IUnknown* pUnk;
HRESULT hr = GetActiveObject(clsid, NULL, (IUnknown**)&pUnk);
if (FAILED(hr))
{
    return false;
}

IDispatch* pDisp;
hr = pUnk->QueryInterface(IID_IDispatch, (void**)&pDisp);
if (FAILED(hr))
{
    return false;
}
pUnk->Release();

driver.AttachDispatch(pDisp);
if (driver.m_lpDispatch == NULL)
{
    driver.CreateDispatch(clsid);
}

CString fileName;
driver.InvokeHelper(0x3, DISPATCH_PROPERTYGET, VT_BSTR, (void*)&fileName, NULL);
xt0899hw

xt0899hw1#

我发现下面的函数可以工作

OLECHAR* GetActiveDocPath()
{
    VARIANT result;
    VariantInit(&result);

    m_hr = OLEMethod(DISPATCH_PROPERTYGET, &result, m_pActiveDocument, (LPOLESTR)L"Path", 0);

    if (FAILED(m_hr))
        return nullptr;

    BSTR docPath = result.bstrVal;

    // Check if the path is a local file path
    if (docPath)
    {
        wchar_t fullPath[MAX_PATH];
        DWORD dwAttrib = GetFileAttributes(docPath);

        // Check if the file exists and is not a directory
        if (dwAttrib != INVALID_FILE_ATTRIBUTES && !(dwAttrib & FILE_ATTRIBUTE_DIRECTORY))
        {
            // Convert the path to a full local path
            DWORD dwSize = GetFullPathName(docPath, MAX_PATH, fullPath, nullptr);

            // Check if the conversion succeeded
            if (dwSize > 0 && dwSize < MAX_PATH)
            {
                // Convert the full path to BSTR
                BSTR resultPath = SysAllocString(fullPath);

                return resultPath;
            }
        }
    }

    return docPath;
}

我把它作为我自己类的一部分,所以你必须定义

IDispatch *m_pActiveDocument;

相关问题