以下过程显示了如何通过 Microsoft.VisualStudio.ProjectEngine.dll,从一些提供的项目模型对象中查找有关 Visual C++ 项目的信息。 此程序集将公开编译器、链接器和其他生成工具,以及 Visual C++ 项目的“属性页”对话框的功能。
你可以将以下过程中的代码集成到名为 TestVCProjectPackage 的 VSPackage 中,它具有一个名为“我的命令名”的菜单命令。 有关如何执行此操作的信息,请参阅演练:使用 Visual Studio 创建包模板的菜单命令。
使用 VCProjectEngine 操作 Visual C++ 项目
添加对 Microsoft.VisualStudio.VCCodeModel(在**“扩展”选项卡上)和 System.Windows.Forms(在“框架”**选项卡上)的引用。
将以下 using 语句添加到 TestVCProjectPackagePackage.cs 文件:
using EnvDTE; using EnvDTE80; using EnvDTE90; using EnvDTE100; using Microsoft.VisualStudio.VCCodeModel; using System.Windows.Forms;
删除 MenuItemCallback 方法中的现有代码。 将代码添加到获取应用程序对象的此方法(在这种情况下为 DTE2:
private void MenuItemCallback(object sender, EventArgs e) { DTE2 dte2 = (DTE2)GetService(typeof(DTE)); }
在同一方法中,获取打开项目。 确保某个项目已实际打开。
private void MenuItemCallback(object sender, EventArgs e) { DTE2 dte2 = (DTE2)GetService(typeof(DTE)); VCProject prj; Projects projColl = dte2.Solution.Projects; if (projColl.Count == 0) { MessageBox.Show("You must have a project open in the experimental instance."); return; } if (projColl.Count > 0) { // to be filled in later } }
获取打开项目并检查项目配置。
private void MenuItemCallback(object sender, EventArgs e) { DTE2 dte2 = (DTE2)GetService(typeof(DTE)); VCProject prj; VCAssemblyReference vcar; int idx; IVCCollection mycollection, mycollection2; VCConfiguration cfg; String sTest = "Configuration Information:" + "\n"; VCFile file; try { Projects projColl = dte2.Solution.Projects; if (projColl.Count == 0) { MessageBox.Show("You must have a project open in the experimental instance."); return; } if (projColl.Count > 0) { prj = (VCProject)dte2.Solution.Projects.Item(1).Object; if (prj.CanAddAssemblyReference(@"%VSINSTALLDIR%\Common7\IDE\PublicAssemblies\VSLangProj.dll")) { vcar = (VCAssemblyReference)prj.AddAssemblyReference(@"%VSINSTALLDIR%\Common7\IDE\PublicAssemblies\VSLangProj.dll"); MessageBox.Show("The assembly named" + vcar.AssemblyName + " was added."); } mycollection = (IVCCollection)prj.Configurations; MessageBox.Show("Number of configurations in the project : " + mycollection.Count); for (idx = 1; idx <= mycollection.Count; idx++) { cfg = (VCConfiguration)mycollection.Item(idx); sTest = sTest + "Configuration name: " + cfg.Name + "\n" + "Platform: " + "\n" + cfg.Platform.ToString() + "\n" + "Program database: \n" + cfg.ProgramDatabase + "\n"; } MessageBox.Show(sTest); mycollection2 = (IVCCollection)prj.Files; MessageBox.Show("Number of files in the project: " + mycollection2.Count); } } catch (SystemException ex) { MessageBox.Show("ERROR: " + ex.ToString()); } }
生成解决方案并启动调试。 将出现 Visual Studio 的第二个实例。 此实例称为实验实例。
在实验实例中打开一个 Visual C++ 项目。
在**“工具”菜单上,单击“我的命令名”**。
命令代码通过使用 VCAssemblyReference 对象添加对 VSLangProj.dll 的引用并显示有关它的信息。 它还通过使用 VCConfiguration 对象枚举和显示所有配置名称。 VCFile 用于显示 Visual C++ 项目中存在的文件扩展名。 VCProject 和 IVCCollection 对象用于将该项目声明为 Visual C++ 项目并枚举配置和文件集合。