Playing with VS macros: Getting the PrimaryOutput
Some things that should be easy are still much harder than they should be. One of those things is writing macros and add-ins for Visual Studio. The object hierachy is (a) obfuscated by a COM/managed interop mess (b) not logically or consistently laid out (c) hard to debug, (d) full of subtle bugs and weird behaviors.
Today I wanted to write a macro to display the generated output of specific VC++ projects. I'll spare you the details of why I want to do this, and just tell you the code that managed finally managed to do it. The following code does it:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports Microsoft.VisualStudio.VCProjectEngine
Imports System.Diagnostics
Public Module Example
Sub DisplayVCProjectOutputs()
For Each proj As EnvDTE.Project In DTE.Solution.Projects
If proj.Kind = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}" Then
Debug.Print("Found VCProject " + proj.Name)
ProcessVCProject(proj)
End If
Next
End Sub
Sub ProcessVCProject(ByVal proj As Project)
Dim configMgr As ConfigurationManager
Dim config As Configuration
Dim configName As String
configMgr = proj.ConfigurationManager
config = configMgr.ActiveConfiguration
configName = config.ConfigurationName + "|" + config.PlatformName
Debug.Print("Active project configuration is " + configName)
Dim vcProj As VCProject
Dim vcConfig As VCConfiguration
vcProj = CType(proj.Object, VCProject)
For Each vcConfig In vcProj.Configurations
If vcConfig.Name = configName Then
Debug.Print("Found configuration")
Exit For
End If
Next
If vcConfig Is Nothing Then
Exit Sub
End If
Debug.Print("Primary output " + vcConfig.PrimaryOutput)
End Sub
End Module
There are a couple of key points to this code. First, it's not obvious but you can cast a EnvDTE.Project object to a VCProject object. However you have to do it on the Object property not the Project itself. That's just nutty. Secondly, you have to use the ConfigurationManager that you get from the EnvDTE.Project to get the correct active EnvDTE.Configuration based on the active solution configuration.