如何调用从一个单独的C#项目一VSTO的外接程序的方法?外接、程序、方法、项目

2023-09-03 01:07:41 作者:别逼我耍流氓

我有一个C#Excel加载项目MyExcelAddIn,有一个公共方法foo()做复杂的东西。出于测试目的,外接还定义了一个工具栏按钮,这是有线美孚()这样我就可以测试一下,并验证单击按钮调用foo()和做什么,我想要它做的。这是好的。

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.

现在我想调用从C#Windows窗体项目中此方法。在Windows窗体项目,我可以创建一个Excel的实例,并使它可见,并确认我的VSTO加载运行,我可以看到按钮和它的作品。但是我不知道如何从Windows窗体项目调用foo()编程。我GOOGLE了一下,得到尽可能获得MyExcelAddInCOMAddIn对象,但无法工作,如何调用foo()。

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().

这看起来是这样的:

// 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...

所以,我想知道我能做些什么来调用foo()从我的Windows窗体应用程序。请注意,我已经在Windows窗体应用程序和外接两种完全控制,我怀疑我必须做出改变,以他们两人(尤其是加载项),但我不知道如何做到这一点。

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.

请注意,这是一个VS2008 C#应用程序,我用Excel 2003。

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

推荐答案

我使用的是SendMessage函数的Win32 API来做到这一点。我的C#外接一个潮头窗口标题的WinForm的应用程序可以找到创建一个的NativeWindow。

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.