Unquestionably, regions make code much cleaner! But they also led to an explosion of method sizes (in number of lines) and the number of methods per file. Long gone is the “rule of thumb” of early 90s of a function size being equal to the visible screen area, or, roughly 20 some lines of code.
Yes, VS has a menu command to expand/collapse code – Edit -> Outlining. The problem for me is that I don’t care to collapse all code… I just want the regions! And, VS is missing this very useful feature!
Thanks to the online community, I found a post by Les Smith called “Collapsing and UnCollapsing All Regions in an Add-in” at http://www.knowdotnet.com/articles/toggleallregions.html. Here is his macro:
Public Sub CloseAllRegions()
Public Sub OpenAllRegions()
Public Sub ToggleAllRegions(ByVal Switch As String)
‘ in walking up through the code, if we do not see
‘ #endregion/end region before we get to the
‘ #region, then the region was closed, otherwise
‘ it was already open, and each time a #region is
‘ found, set open = false as we are only looking
‘ for closed regions and if we toggle an open region
‘ it will close…
Dim cmd As String = “Edit.ToggleOutliningExpansion”
Dim open As Boolean = False
Dim ts As TextSelection = DTE.ActiveDocument.Selection
Dim ep As EditPoint = ts.ActivePoint.CreateEditPoint
Dim line As String
Do While Not ep.AtStartOfDocument
line = ts.Text.ToLower.Trim
If line.StartsWith(“#end region”) Or _
open = True
ElseIf line.StartsWith(“#region “) Then
If Switch = “C” Then
If open Then
If Not open Then
open = False
ep = ts.ActivePoint.CreateEditPoint
All you need to do is:
- Open Macro IDE (Alt + F11)
- Double click on MyMacros -> Module1 and past the code above between Public Module Module1 and End Module lines
- Open Tools -> Customize form, and click on Commands tab. Then click Keyboard… button at the bottom.
- In the Show Commands Containing… list box, press M, and scroll down until you have Macros.MyMacros.Module1.CloseAllRegions selected.
- Change focus to Press Shortcut Keys text box, and choose the shortcut of your choice (I use Ctrl+Alt+C, Ctrl+Alt+C).
- Now do the same for Macros.MyMacros.Module1.OpenAllRegions.
Alternatively, you can create a toolbar for these macros using Tools -> Customize -> Toolbars dialog. For a more verbose description on how to create custom toolbars and add your own toolbar buttons, visit http://www.codeguru.com/csharp/.net/net_vs_addins/visualstudionet2003add-ins/article.php/c5955/ and scroll about half way down to the “Integrating the Macro Code Generator into the IDE” section.
You’re now able to expand and collapse all regions with a keyboard shortcut!