Blog Archives

Macro To Collapse Expanded Projects In Solution Explorer

If you’ve ever worked on a solution which has too many projects, you would find it took a lot of time to ‘manually’ collapse expanded projects once opening the solution on Visual Studio’s Solution Explorer.

Here is a macro which does that for you. Just open VS, create a VS Macro Project by going to Tools > Macros > New Macro Project. VS will create a new macro project named MacroProject1 and show that project in Macro Explorer. Under MacroProject1, there is a module named Module1. Right click on Module1 and select Edit, VS then brings out Module Editor. Copy and paste this piece of code for the module:

Imports System

Imports EnvDTE
Imports EnvDTE80
Imports System.Diagnostics

Public Module CollapseSelectedNode

Sub CollapseSelected()
‘ Get the the Solution Explorer tree
Dim UIHSolutionExplorer As UIHierarchy
UIHSolutionExplorer = DTE.Windows.Item(Constants.vsext_wk_SProjectWindow).Object()

‘ Check if there is any open solution
If (UIHSolutionExplorer.UIHierarchyItems.Count > 0) Then

‘ Get the selected node
Dim UIHSolutionRootNode As UIHierarchyItem
UIHSolutionRootNode = UIHSolutionExplorer.SelectedItems(0)

UIHSolutionRootNode.DTE.SuppressUI = True

‘ Collapse each project node
Dim UIHItem As UIHierarchyItem
For Each UIHItem In UIHSolutionRootNode.UIHierarchyItems
If UIHItem.UIHierarchyItems.Count > 0 And UIHItem.UIHierarchyItems.Expanded Then
‘ As of a Bug in VS 2005 you have to use the following lines
‘ instead of using UIHItem.UIHierarchyItems.Expended = False
End If

UIHSolutionRootNode.DTE.SuppressUI = False
End If
End Sub

Your module editor might look like below:

Macro Editor

Press Ctrl + S to save the module. Now it’s time to bind shortcut keys to execute the module once pressed. Go to Tools > Options, expand ‘Environment’ node then select ‘Keyboard’ subnode. Enter the fully qualified name of the macro you just created in ‘Show command containing’ text box, i.e. Macros.MacroProject1.CollapseSelectedNode.CollapseSelected. Place mouse cursor in ‘Press shortcut key’ text box then press Ctrl + Alt + / (you can choose other combination of keys if you want to).  Your screen might look like below:

Shortcut keyboard binding to macro

Click OK to bind the shortcut keys to the macro. Now, it’s time to test the macro by opening any .NET solution, expand some projects under that solution then press ‘Ctrl + Alt + /’ you will see all the expanded projects are collapsed.