I have had this question a number of times and surprised myself when I did not see it in my blog. So here goes.
There are times when (like my Master Add-in Entry), you need to expose a set of methods or properties in your add-in so that other add-ins or applications are able to access them. Here is how it is done:
1) You create an interface and a class that uses that interface, like this:
[ComVisibleAttribute(true)] public interface IExposedMethods { void LoadDocument(string path); } [ComVisibleAttribute(true)] [ClassInterface(ClassInterfaceType.None)] public class ExposedClass : IExposedMethods { public void LoadDocument(string path) { Globals.ThisAddIn.Application.Workbooks.Open(path); } }
2) Next, you need to add the following code to your ThisAddin.cs:
private ExposedClass _exposedInstance; protected override object RequestComAddInAutomationService() { if (_exposedInstance == null) _exposedInstance = new ExposedClass(); return _exposedInstance; }
3) And finally, to call it and access this from another application instance, you do this:
Excel.Application xlApp = new Excel.Application(); xlApp.Visible = true; object addinName = "MyAddinName"; Office.COMAddIn addIn = xlApp.COMAddIns.Item(ref addinName); addIn.Object.LoadDocument(@"c:\path\test.xlsm");
It is actually quite easy to implement. And the beauty here is that the ExposedClass you created can have all sorts of methods and properties that are exposed. And because the _exposedInstance is global to ThisAddIn (via Globals.ThisAddin._exposedInstance), you can access it anywhere. So it is a perfect way for one add-in to contact another or for a parent Windows Form application to reach into the Add-in and set properties and call methods and have it open documents and such for you.