Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 which is wired to Foo() so I can test this and verify that clicking the button calls Foo() and does what I want it to do. This is fine.

Now I want to call this method from a C# Windows Forms project. In the Windows Forms project I can create an Excel instance and make it visible and verify that my VSTO add-in is running as I can see the button and it works. But I can't work out how to call Foo() programatically from the Windows Forms project. I've googled a bit and got as far as getting the "MyExcelAddIn" COMAddIn object, but can't work out how to call Foo().

It looks something like this:

// Create Excel and make it visible
Application excelApp = new Application();
excelApp.Visible = true;

// I know my VSTO add-in is running because I can see my test button
// Now get a reference to my VSTO add-in
Microsoft.Office.Core.COMAddIns comAddIns = _excelApp.COMAddIns;
object addinName = "MyExcelAddIn";
Microsoft.Office.Core.COMAddIn myAddin = comAddIns.Item(ref addinName);
// This works, but now what? How do I make a call on myAddin?
// Note that myAddin.Object is null...

So I want to know what I can do to call Foo() from my Windows Forms application. Note that I have full control over both the Windows Forms application and the add-in and I suspect I have to make changes to both of them (particularly the add-in) but I have no idea how to do this.

Note that this is a VS2008 C# application and I'm using Excel 2003.

like image 809
Ben Robbins Avatar asked Feb 13 '09 07:02

Ben Robbins


2 Answers

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.
like image 60
Michael Regan Avatar answered Nov 19 '22 17:11

Michael Regan


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.

like image 35
Dan Byström Avatar answered Nov 19 '22 18:11

Dan Byström