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 |