Unable to cast DTE, project or solution to VCProje

2019-04-26 16:40发布

问题:

I am trying to get some information about c+= programs, through code. I have had some success with EnvDTE, now I need to use VCProject and VCCodeModel and I am running into casting problems (hope that is all...)

In the working class, I have a DTE "application" passed from the Connect.

I have:

EnvDTE.Project project = application.SelectedItems.Item(1).Project;
EnvDTE.Solution sol = (EnvDTE.Solution)application.Solution;

I would like to use "project", not the first project in the solution as the examples I have found on the web - as below - but mostly, I would like to have something that works first.

For VCProject, I have tried (off Microsoft's web site, and all other web examples):

VCProject vcProject = (VCProject)application.Solution.Projects.Item(1).Object;
MessageBox.Show(vcProject.ProjectDirectory);

or... just

VCProject vcProject = (VCProject)project.Object;

For VCCodeModel, I translated to c# http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.vccodemodel.vccodeinclude.aspx:

public void GetAllIncludes()
{
  VCCodeModel vcCM = (VCCodeModel)application.Solution.Item(1).CodeModel;
  foreach (VCCodeInclude vcInclude in vcCM.Includes)
  {
    MessageBox.Show(vcInclude.DisplayName);
  }    
}

Both give exception:

"unable to cast com object of type 'system.__comobject' to interface type Microsoft.VisualStudio.VCCodeModel"
"unable to cast com object of type 'Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.VCProjectShim' to type Microsoft.VisualStudio.Project.VisualC.VCProjectEngine.VCProject"

How can I set this up ? Preferably using the "project"... or application.SelectedItems... Is it possible ?

Can somebody please give me an idea? Thank you.

回答1:

This problem arises when you try to cast CodeModel to a different VCCodeModel version. There is a VCCodeModel.dll for each VS version.