添加过滤器到visual studio模板

时间:2013-06-28 13:45:12

标签: c++ visual-studio visual-studio-2012 visual-studio-templates

我正在尝试使用向导在Visual Studio(C ++)项目模板中创建一个过滤器(除了项目中的文件之外什么都不做的小文件夹之一),所以我在下面编写以下代码RunStarted方法:

public void RunStarted(object automationObject,
        Dictionary<string, string> replacementsDictionary,
        WizardRunKind runKind, object[] customParams)
    {
      try
      {
        // Add filters to the project
        EnvDTE.DTE dte = (EnvDTE.DTE)automationObject;

        Array activeProjects = (Array)dte.ActiveSolutionProjects;
        Project activeProj = (Project)activeProjects.GetValue(0);
        VCProject prj = (VCProject)activeProj.ProjectItems.Item(0);
        VCFilter filter = prj.AddFilter("Header_Files");
        filter.AddFile("header.h");
        prj.Save();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.ToString());
      }
    }

但这失败了。返回的错误是:

  

System.IndexOutOfRangeException:索引超出了范围   阵列。

     

在System.Array.InternalGetReference(Void * elemRef,Int32 rank,   Int32 * pIndices)

     

在System.Array.GetValue(Int32索引)

     

at my_wizard.IMyWizard.RunStarted(Object automationObject,   Dictionary`2 replacementsDictionary,WizardRunKind runKind,Object []   customParams)

我哪里出错了?如何向vs模板添加过滤器?

1 个答案:

答案 0 :(得分:1)

您可以找到答案here 有人说当解决方案资源管理器未打开时会出现问题 这是我基于上层链接的解决方案:

    private Project getActiveProject(DTE2 dte)
    {
        Array projects = dte.ActiveSolutionProjects as Array;
        if (projects == null || projects.Length == 0)
        {
            projects = dte.Solution.SolutionBuild.StartupProjects as Array;
            if (projects == null || projects.Length == 0)
            {
                Projects pro = dte.Solution.Projects;
                if (pro == null || pro.Count == 0)
                    return null;
                return pro.Item(0);
            }
        }
        return projects.GetValue(0) as Project;
    }