COMAddIn.Object始终为Null

时间:2018-07-24 20:30:50

标签: outlook vsto

我正在尝试使用VSTO Outlook插件实现电子邮件功能。但 由于这个原因我无法将ComAddIn.Object始终为null 访问VSTO加载项的成员

  Outlook.Application OutlookObj = new Outlook.Application();
        object AddinName = "OutlookAddIn";
        COMAddIn AddIn = OutlookObj.COMAddIns.Item(ref AddinName);
        IOutLookApp utils = (IOutLookApp)AddIn.Object;
        utils.CallOlMethod();

这是TheAddIn.cs

namespace OutlookAddIn
{
public interface IOutLookApp
{
    void CallOlMethod();
}  

public partial class ThisAddIn
{
    protected override object RequestComAddInAutomationService()
    {
        OutlookApp ol = new OutlookApp();
        return ol;
    }
    #region VSTO generated code
    private void ThisAddIn_Startup(object sender, System.EventArgs e)
    {
    }

    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
    }
    /// <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
public void CreateOutlookItem()
{
    Outlook.MailItem newEmail = new Outlook.MailItem
    {
        To = "example@gmail.com",
        Subject = "testing",
        Importance = Outlook.OlImportance.olImportanceLow
    };
    newEmail.Send();
}
}
public class OutlookApp:
   StandardOleMarshalObject,
    IOutLookApp
{
    public void CallOlMethod()
    {
        Globals.ThisAddIn.CreateOutlookItem();
    }
}
}

我在这里做错了什么?虽然我的AddIn类公开了,但ComAddIn.Object为null,为什么?请帮助解决问题。

1 个答案:

答案 0 :(得分:0)

要将您的VSTO加载项公开给外部调用者,请执行以下步骤:

  1. 将接口定义为双接口,并使它可见 [ComVisible(true)] [InterfaceType(ComInterfaceType.InterfaceIsDual)] public interface IOutLookApp { void CallOlMethod(); }
  2. 还定义一个实现接口的类,如下所示 [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] public class OutlookApp : StandardOleMarshalObject, IOutLookApp { public void CallOlMethod() { //do something } }

了解更多:Call code in VSTO Add-ins from other Office solutionsVSTO Add-ins, COMAddIns and RequestComAddInAutomationService

编辑: 还需要检查项目设置中的“注册Com互操作” ,并确保以管理员身份运行Visual Studio。