KnowDotNet Visual Organizer

Collapse a Region Programatically in an Add-In.

by Les Smith and Brian Davis
Print this Article Discuss in Forums

I have seen the question on Microsoft and Other Newsgroups asking, "How can I collapse a Region Programatically in a Visual Studio .NET Add-In?  What seems a great mystery, because the IDE does not expose a command that you would think that would do this, is actually a piece of cake!

Although I am writing the article, regarding Add-Ins, I have to give my partner Bria Davis credit for finding the solution.  

If you place the cursor anywhere in the #Region (VB.NET) or #region in C# (CSharp), and select the Edit, Outlining, ToggleOutliningExpansion, the region will collapse!  Now the problem is how can I get the cursor to move from where the user has it, somewhere in the region, to position in the #Region line?  The following code will do it for you.

You can test this code by coping into the Macro IDE, set your cursor somewhere below the #Region line that you want to collapse, and double-click on the Sub in the Macro Explorer.  A little explanation of the Macro/Add-In code; first, I create a TextSelection object of the current Visual Studio .NET IDE CodeWindow.  Next, I create and EditPoint object set to the ActivePoint of the TextSelection object.  This causes the EditPoint Line Property to be set to the line in which the cursor resides in the current CodeWindow.  I then search backwards through the CodeWindow until I find the desired text.  For C#, the "#region" is lower case, while in VB.NET "#Region" is capitalized.  

    Public Sub CollapseCurrentRegion()
        
Dim ts As TextSelection = DTE.ActiveDocument.Selection
        
Dim ep As EditPoint = ts.ActivePoint.CreateEditPoint
        
Dim line As String

        Do While Not ep.AtStartOfDocument
            ep.StartOfLine()
            line = ep.GetText(ep.LineLength).Trim
            
' the next line will be different for c# (#region)
            If line.StartsWith("#Region ") Then
                ts.MoveToLineAndOffset(ep.Line, 1)
                DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
                
Exit Do
            End If
            ep.LineUp(1)
        
Loop
    End Sub

To use this code in an add-in, simply replace DTE with the name of the applicationObject in the add-in.  Visual Studio .NET Add-Ins are not hard to write, once you figure out which object, method, property, etc., in the vast Extensibility Model to use.

Actually, you could collapse the current Class, NameSpace, or even the method, in which the cursor currently resides, by using a modification of the search string in the example code shown above.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing