我需要开发2个VSTO项目程序:
- VSTO for PPT
- VSTO for Word
在PPT程序中,唤醒/打开 Word 程序,并执行 Word 中 VSTO 代码.
代码如下:
PPT中唤醒/打开 Word:
//获取word程序
Word.Application wordApp;
try { wordApp = Marshal.GetActiveObject("Word.Application") as Word.Application; }
catch { wordApp = new Word.Application(); }
wordApp.Visible = true;
wordApp.Documents.Add();
wordApp.Activate();
COMAddIn comaddin = wordApp.COMAddIns.Item("BaxEduWord");
System.Windows.MessageBox.Show(comaddin.Object.test("rrrrr"));
Word 中暴露 VSTO 对象,让 PPT程序中调用:
创建 AddInUtilities.cs
using System.Runtime.InteropServices;
namespace BaxEduWord
{
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
public interface IAddInUtilities
{
string test(string inp);
}
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
public class AddInUtilities : StandardOleMarshalObject, IAddInUtilities
{
public string test(string inp)
{
return inp;
}
}
}
在 ThisAddIn
中重写RequestComAddInAutomationService
暴露对象:
/// <summary>
/// 暴露当前VSTO模型
/// </summary>
private AddInUtilities utilities;
protected override object RequestComAddInAutomationService()
{
if (utilities == null)
utilities = new AddInUtilities();
return utilities;
}
然后我运行 PPT 程序,出现错误:ppt
成功的将Word
唤醒,并且得到word
的application
,
但从application
中希望得到word
的外界程序COMAddIns
时出现异常:
我尝试了下面办法:
对比一下注册表版本信息:
1,计算机HKEY_CLASSES_ROOTWOW6432NodeInterface{00020970-0000-0000-C000-000000000046}TypeLib
2,HKEY_CLASSES_ROOTWOW6432NodeTypeLib{00020905-0000-0000-C000-000000000046}
电脑曾经安装过 WPS
上面代码原封不动 在同事电脑上可以正常运行 !!!
使用下面封装的互操作类: