Outlook VSTO加载项与外部C ++应用程序之间的交互

时间:2018-09-19 05:05:11

标签: c# c++ outlook com vsto

我有一个C ++应用程序,并且正在编写一个新的Outlook加载项,我认为它将与VSTO一起使用。我想在那时之间进行交流,并试图找出最好的方法。在MS docs上,他们提到了如何使用RequestComAddInAutomationService将COM类公开给外部解决方案。我是COM的新手,但我在网上阅读了一些内容,并获得了以下解决方案。我读到您应该构建外接程序(将x86作为Outlook版本而不是AnyCPU),采用创建的.tlb文件,然后使用.tlh将其转换为#import指令,然后#include .tlh文件具有适当的类型。

ThisAddin.cs

namespace FirstOutlookAddIn
{

public partial class ThisAddIn
{
    Outlook.Inspectors inspectors;
    private AddInUtilities gUtilities;

    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
        inspectors = this.Application.Inspectors;
        inspectors.NewInspector +=
        new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(Inspectors_NewInspector);
    }

    void Inspectors_NewInspector(Microsoft.Office.Interop.Outlook.Inspector Inspector)
    {
        Outlook.MailItem mailItem = Inspector.CurrentItem as Outlook.MailItem;
        if (mailItem != null)
        {
            if (mailItem.EntryID == null)
            {
                gUtilities.SetMailItem(mailItem);
                mailItem.Subject = "This text was added by using code";
                mailItem.Body = "This text was added by using code";
            }

        }
    }

    protected override object RequestComAddInAutomationService()
    {
        if (gUtilities == null)
            gUtilities = new AddInUtilities();

        return gUtilities;
    }

    private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
    {
        // Note: Outlook no longer raises this event. If you have code that 
        //    must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
    }

    #region VSTO generated code

    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InternalStartup()
    {
        this.Startup += new System.EventHandler(ThisAddIn_Startup);
        this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
    }

    #endregion
}

}

IAddInUtilities.cs

using System.Runtime.InteropServices;
namespace FirstOutlookAddIn
{
    [ComVisible(true)]
    public interface IAddInUtilities
    {
        void MyExportedFunction();
    }
}

AddInUtilities.cs

using Outlook = Microsoft.Office.Interop.Outlook;
using System.Runtime.InteropServices;
namespace FirstOutlookAddIn
{
    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class AddInUtilities : StandardOleMarshalObject, IAddInUtilities
    {
        Outlook.MailItem globalMailItem;
        public void SetMailItem(Outlook.MailItem item) => globalMailItem = item;
        public void MyExportedFunction()
        {
            globalMailItem.Body = "I was called from outside!";
        }
    }
}

main.cpp

//#import "FirstOutlookAddIn.tlb" named_guids raw_interfaces_only

#include <iostream>
struct IUnknown; // Workaround for "combaseapi.h(229): error C2187: syntax error: 'identifier' was unexpected here" when using /permissive-
#include <Objbase.h>
#include "Debug\FirstOutlookAddIn.tlh"

int main() {
    CoInitializeEx(nullptr, COINIT_MULTITHREADED);
    FirstOutlookAddIn::IAddInUtilities* pIFace;
    // create the object and obtain a pointer to the sought interface
    auto res = CoCreateInstance(
        FirstOutlookAddIn::CLSID_AddInUtilities,
        nullptr,
        CLSCTX_LOCAL_SERVER,
        FirstOutlookAddIn::IID_IAddInUtilities,
        (LPVOID*)&pIFace);
    if (res != S_OK)
    {
        std::cout << "Failed with: " << res;
    }
    auto res1 = pIFace->MyExportedFunction(); // use the object
    std::cout << "Res: " << res1;
    pIFace->Release(); // free the object
    CoUninitialize();
}

问题是CoCreateInstance返回REGDB_E_CLASSNOTREG Class not registered。相关的注册表树如下所示:

HKEY_LOCAL_MACHINE \ SOFTWARE \ WOW6432Node \ Classes \ CLSID {5008A102-08E5-3F59-AADD-03875524CAD0} = FirstOutlookAddIn.AddInUtilities 计算机\ HKEY_LOCAL_MACHINE \ SOFTWARE \ WOW6432Node \ Classes \ CLSID {5008A102-08E5-3F59-AADD-03875524CAD0} \ InprocServer32: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Classes\CLSID{5008A102-08E5-3F59-AADD-03875524CAD0}\InprocServer32 计算机\ HKEY_LOCAL_MACHINE \ SOFTWARE \ WOW6432Node \ Classes \ CLSID {5008A102-08E5-3F59-AADD-03875524CAD0} \ InprocServer32 \ 1.0.0.0: Computer\HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Classes\CLSID{5008A102-08E5-3F59-AADD-03875524CAD0}\InprocServer32\1.0.0.0 Computer \ HKEY_LOCAL_MACHINE \ SOFTWARE \ WOW6432Node \ Classes \ CLSID {5008A102-08E5-3F59-AADD-03875524CAD0} \ ProgId = FirstOutlookAddIn.AddInUtilities

我在做什么错?我是否正确理解了这里的可能性,即将DLL加载到Outlook.exe中并能够从外部应用程序调用其中的功能? 在此先感谢!

2 个答案:

答案 0 :(得分:1)

您不应该从C ++应用程序创建该COM类的实例-创建Outlook.Application对象的实例,使用Application.COMAddins集合来获取您的插件,然后使用{{1 }}属性以检索由您的插件实现的接口。
例如,参见https://blogs.msdn.microsoft.com/andreww/2007/01/15/vsto-add-ins-comaddins-and-requestcomaddinautomationservice/

答案 1 :(得分:1)

经过一番摸索,我发现了。我正在使用Microsoft的CppAutomateOutlook example

它有2种实现选项,一种使用COM的智能指针(例如spMail->Subject = _bstr_t(L"Feedback of All-In-One Code Framework");),另一种使用原始的IDispatch接口。我使用了第二个选项,并将CoCreateInstance修改为GetActiveObject,以便可以与已经运行的Outlook实例进行交互。这是我当前的代码:

DWORD WINAPI AutomateOutlookByCOMAPI(LPVOID lpParam)
{
    // Initializes the COM library on the current thread and identifies 
    // the concurrency model as single-thread apartment (STA). 
    // [-or-] CoInitialize(NULL);
    // [-or-] CoCreateInstance(NULL);
    CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);

    // Define vtMissing for optional parameters in some calls.
    VARIANT vtMissing;
    vtMissing.vt = VT_EMPTY;

    // Get CLSID of the server
    CLSID clsid;
    HRESULT hr;

    // Option 1. Get CLSID from ProgID using CLSIDFromProgID.
    LPCOLESTR progID = L"Outlook.Application";
    hr = CLSIDFromProgID(progID, &clsid);
    if (FAILED(hr))
    {
        wprintf(L"CLSIDFromProgID(\"%s\") failed w/err 0x%08lx\n", progID, hr);
        return 1;
    }
    // Option 2. Build the CLSID directly.
    /*const IID CLSID_Application = 
    {0x0006F03A,0x0000,0x0000,{0xC0,0x00,0x00,0x00,0x00,0x00,0x00,0x46}};
    clsid = CLSID_Application;*/

    // Get the IDispatch interface of the running instance

    IUnknown *pUnk = NULL;
    IDispatch *pOutlookApp = NULL;
    hr = GetActiveObject(
        clsid, NULL, (IUnknown**)&pUnk
    );

    if (FAILED(hr))
    {
        wprintf(L"GetActiveObject failed with w/err 0x%08lx\n", hr);
        return 1;
    }

    hr = pUnk->QueryInterface(IID_IDispatch, (void **)&pOutlookApp);
    if (FAILED(hr))
    {
        wprintf(L"QueryInterface failed with w/err 0x%08lx\n", hr);
        return 1;
    }

    _putws(L"Outlook.Application is found");

    IDispatch *comAddins = NULL;
    {
        VARIANT result;
        VariantInit(&result);
        AutoWrap(DISPATCH_PROPERTYGET, &result, pOutlookApp, L"COMAddins", 0);
        comAddins = result.pdispVal;
    }

    IDispatch *myAddin = NULL;
    {
        VARIANT x;
        x.vt = VT_BSTR;
        x.bstrVal = SysAllocString(L"FirstOutlookAddIn");

        VARIANT result;
        VariantInit(&result);
        AutoWrap(DISPATCH_METHOD, &result, comAddins, L"Item", 1, x);
        myAddin = result.pdispVal;

        VariantClear(&x);
    }

    IDispatch *myAddinObj = NULL;
    {
        VARIANT result;
        VariantInit(&result);
        AutoWrap(DISPATCH_PROPERTYGET, &result, myAddin, L"Object", 0);
        myAddinObj = result.pdispVal;
    }

    {
        VARIANT result;
        VariantInit(&result);
        AutoWrap(DISPATCH_METHOD, &result, myAddinObj, L"MyExportedFunction", 0);
    }

    // ... Cleanup code
}