如何:编译和运行自动化对象模型代码示例
更新:2007 年 11 月
在自动化对象模型参考主题中找到的代码示例设计为在用“外接程序向导”创建的外接程序中运行。此外,Visual Basic 代码示例可以宏的形式运行。以下几节介绍了如何编译和运行自动化对象模型代码示例。
在外接程序中运行代码示例
使用“外接程序向导”创建外接程序。
有关更多信息,请参见如何:创建外接程序。
将代码示例添加至外接程序的 Connect 类。
从外接程序的 OnConnection 方法中调用代码示例过程。如果代码示例要求 DTE2 对象作为变量,请传入在外接程序代码中声明的 _applicationObject 成员变量。下面的代码显示了 Visual Basic 和 Visual C# 外接程序中 Connect 类的相关部分:
Public Sub OnConnection(ByVal application As Object, ... ) _ Implements IDTExtensibility2.OnConnection _applicationObject = CType(application, EnvDTE80.DTE2) . . . ' Pass the _applicationObject member variable to the code ' example. MyCodeExample(_applicationObject) End Sub ' Other methods in the Connect class. . . . ' This is the code example that was added to the Connect class. Sub MyCodeExample(ByVal dte As DTE2) . . . End Sub
public void OnConnection(object application, ... , ref Array custom) { _applicationObject = (_DTE2)application; . . . // Pass the _applicationObject member variable to the code // example. MyCodeExample(_applicationObject); } // Other methods in the Connect class. . . . // This is the code example that was added to the Connect class. void MyCodeExample(DTE2 dte) { . . . }
对于 Visual C# 外接程序,可以通过以下方式添加对 System.Windows.Forms 程序集的引用:单击“解决方案资源管理器”中外接程序项目的名称,从“项目”菜单中选择“添加引用”,然后在“添加引用”对话框中选择 System.Windows.Forms.dll。
对于 Visual C# 外接程序,在 Connect.cs 文件的顶部插入下面的代码:
using System.Windows.Forms;
通过从“生成”菜单中选择“生成解决方案”来编译外接程序。
从“工具”菜单中选择“外接程序管理器”。
出现“外接程序管理器”对话框。
在“外接程序管理器”对话框中,选择外接程序名称旁边的复选框以加载此外接程序,然后单击“确定”。
将 Visual Basic 代码示例以宏的形式运行
在“工具”菜单上指向“宏”,再单击“宏 IDE”。
出现“宏 IDE”。
在“宏 IDE”的“视图”菜单上单击“项目资源管理器”。
展开“项目资源管理器”中的 MyMacros 节点。
双击 Module1。
将代码示例添加至此模块文件。
如果代码示例要求 DTE 对象作为变量,请创建一个不带参数的宏,用于将全局 DTE 变量传递到代码示例。下面的代码显示如何做:
' Visual Basic ' Macro without parameters that calls the code example. Sub CodeExample() CodeExample(DTE2) End Sub ' Original code example. Sub CodeExample(ByVal dte As DTE2) . . . End Sub
关闭“宏 IDE”。
在 Visual Studio IDE 中的“工具”菜单上指向“宏”,再单击“宏资源管理器”。
出现“宏资源管理器”窗口。
在“宏资源管理器”中,展开“MyMacros”节点,再展开“Module1”节点。
在“宏资源管理器”中,右击代码示例宏名称,再从快捷菜单中选择“运行”。