How to call a VSTO AddIn method from a separate C# project?

前端 未结 4 2077
情深已故
情深已故 2020-12-10 07:14

I have a C# Excel Add-in project \"MyExcelAddIn\" that has a public method Foo() to do something complex. For testing purposes, the add-in also defines a toolbar button whic

相关标签:
4条回答
  • 2020-12-10 07:30

    I'm using the SendMessage Win32 API to do this. My C# Add-in creates a "NativeWindow" with a uniqe window title that the WinForm app can locate.

    0 讨论(0)
  • 2020-12-10 07:32

    For anyone else who finds this here's what I did:

            object addInName = "AddinName";
            var excelApplication = (Microsoft.Office.Interop.Excel.Application)Marshal.GetActiveObject("Excel.Application");
            COMAddIn addIn = excelApplication.COMAddIns.Item(ref addInName);
    
            addIn.Object.AddinMethodName(params);
    

    Also had to add a reference to Microsoft.Office.Core under COM and Excel.Interop under Assemblies.

    0 讨论(0)
  • 2020-12-10 07:37

    If you're building an application-level add-in, I believe this may be your answer: MSDN VSTO Article

    It involves two steps: (From the article)

    1. In your add-in, expose an object to other solutions.
    2. In another solution, access the object exposed by your add-in, and call members of the object.

    The other solution may be: (Again from the article)

    • Any solution that is running in a different process than your add-in (these types of solutions are also named out-of-process clients). These include applications that automate an Office application, such as a Windows Forms or console application, and add-ins that are loaded in a different process.
    0 讨论(0)
  • 2020-12-10 07:42

    I assume that your method Foo somehow interacts with Excel. Otherwise you can just add a reference to the assembly containing the class with the Foo method and call it from there without instantiating Excel.

    The only other way I can think is to get a reference to your CommandBarButton through the excelApp object. CommandBarButton has a method called Execute which is similar to clicking the button. Something like this:

            Excel.Application excelApp = new Excel.Application(); 
            CommandBarButton btn = excelApp.CommandBars.FindControl(...) as CommandBarButton;
            btn.Execute();
    
    0 讨论(0)
提交回复
热议问题