Random Musings of Jeremy Jameson

Visual Studio Macro for Collapsing All Items in Solution Explorer

Along with my Visual Studio macros for unloading/reloading projects in a solution, another macro that I use just as much, if not more frequently, is my CollapseAllItems() macro:

Public Sub CollapseAllItems()
    Dim solutionExplorer As Window = _
        DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer)

    solutionExplorer.Activate()

    DTE.SuppressUI = True

    Try
        Dim solutionHierarchy As UIHierarchy = solutionExplorer.Object

        For Each item As UIHierarchyItem _
            In solutionHierarchy.UIHierarchyItems

            CollapseItem(item, solutionHierarchy)
        Next
    Catch ex As Exception
        WriteOutput("Error collapsing all items: " _
            & ex.Message)

    Finally
        DTE.SuppressUI = False
    End Try
End Sub

The CollapseItem() method is used to recursively collapse each item in the hierarchy:

Private Sub CollapseItem( _
    ByVal item As UIHierarchyItem, _
    ByVal solutionHierarchy As UIHierarchy)

    For Each child As UIHierarchyItem In item.UIHierarchyItems
        CollapseItem(child, solutionHierarchy)

        If (item.UIHierarchyItems.Expanded = True) Then
            WriteOutput("Collapsing item (" & item.Name & ")...")
            item.UIHierarchyItems.Expanded = False

            ' HACK: Known bug in Visual Studio 2005
            ' http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=114597
            If (item.UIHierarchyItems.Expanded = True) Then
                item.Select(vsUISelectionType.vsUISelectionTypeSelect)
                solutionHierarchy.DoDefaultAction()
            End If
        End If
    Next
End Sub

While it is great that Visual Studio "synchronizes" the Solution Explorer window to show the current file in the solution hierarchy, in large Visual Studio solutions, things can get a bit bewildering at times if many of the projects are expanded down to the level of individual files.

Perhaps in a future version of Visual Studio, we'll have the ability to right-click the solution in Solution Explorer and then click something like Collapse All. Until then, I don't see me giving up my dependency on this macro anytime soon.

Published Wednesday, March 11, 2009 8:18 AM by Jeremy Jameson
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker