How to call VSTO class from other c# project

前端 未结 2 439
[愿得一人]
[愿得一人] 2021-01-07 04:48

In my solution I have 2 projects.

One is the controller, which in the final product is used to check if a execution is issued from console/non user input and therefo

相关标签:
2条回答
  • 2021-01-07 05:14

    First, to your Addin that you want to call into add an Interface:

    [ComVisible(true)]
    public interface IExcelUtilities
    {
        bool DoSomething();
    }
    

    Next, add a class that implements the interface:

    [ComVisible(true)]
    [ClassInterface(ClassInterfaceType.None)]
    public class AddInUtilities : 
        StandardOleMarshalObject,
        IExcelUtilities
    {
        public bool DoSomething()
        {
            return true;
        }
    }
    

    Then override object RequestComAddInAutomationService in ThisAddin.cs:

    private AddInUtilities utilities;
    
    protected override object RequestComAddInAutomationService()
    {
       try
       {
           if (utilities == null)
           {
               utilities = new AddInUtilities();
           }
    
           return utilities;
        }
        catch (System.Exception ex)
        {
             // Catch your ex here
        }
    }
    

    Now you should be able to call the exposed method from your external application like this:

    foreach (COMAddIn comaddin in addins)
    {
         if (comaddin.ProgId.Equals("YourAddinNameHere", StringComparison.InvariantCultureIgnoreCase) == true)
         {
                  bool returnvalue = comaddin.Object.DoSomething();
                  break;
         }
    }
    

    for some more deep info on this subject, also read: http://blogs.msdn.com/b/andreww/archive/2008/08/11/why-your-comaddin-object-should-derive-from-standardolemarshalobject.aspx

    Hope it helps :-)

    0 讨论(0)
  • This isn't an answer exactly, but for others coming across this, document-level solutions cannot expose interfaces to other solutions.

    Expose an object in a VSTO Add-in to other Microsoft Office solutions.

    • VSTO Add-in projects. Call code in VSTO Add-ins from other Office solutions
    0 讨论(0)
提交回复
热议问题