Click here to Skip to main content
Click here to Skip to main content

A nice macro that automates the task of making regions in C# code

, 3 Jan 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
At ComponentScience where I work, we heartily embrace the use of regions to logically separate our code into meaningful blocks. After doing it manually for a couple of years, I decided to write myself a little macro to make my life easier.



At ComponentScience, we heartily embrace the use of regions to logically separate our code into meaningful blocks. After doing it manually for a couple of years, I decided to write myself a little macro to make my life easier. After a little research, I found a couple of examples of how to manipulate Visual Studio's code editor. The result is the following macro that I use to regionify my code.

I have also included instructions on how to install it into Visual Studio and assign it to a hotkey. I use Alt+R because it wasn't used in the Visual Studio text editor, and it made sense to me.

You are welcome to use it all you want, give it to your friends and even claim to have written it yourself if you want.

Note: I only use this macro in C# files. If you want to use it in VB, then you need to uncomment the VB sections and comment out the C# sections. If anybody has any tips on how to modify the script to detect the language being used, let me know and I will modify the script accordingly. I'm sure there is an easy way, I just haven't researched it because I don't care. The VB parts do work in VB code though. I tested it that much.

Update: After posting this article on CodeProject, I got some feedback from readers about how to test for the language being used, make the padding better, and handle tabs as well as spaces. I have updated the macro accordingly.

Even more update!: The users on CodeProject have done a wonderful job of tweaking the macro! We now have a really nice regioning macro. I am very happy with the feedback I have gotten from the CodeProject community. Special thanks (in no particular order) goes to RussKie, simonech, Hrusikesh, ERobishaw, isler-j, and SvenRieke. These guys embody the spirit of cooperative development.

Macro Code

  Sub MakeRegion()
  End Sub

  Public Class Regions
    ' MakeRegion inserts #region and #endregion tags
    ' around selected text in the VS editor.
    Shared Sub MakeRegion()
      Dim rName As String = ""
      Dim pad As String = ""
      Dim junk As String
      Dim count, i As Integer
      Dim startpoint, endpoint, tmppoint As EditPoint

      With DTE.ActiveDocument.Selection
        startpoint = .TopPoint.CreateEditPoint()
        endpoint = .BottomPoint.CreateEditPoint
      End With

      If startpoint.EqualTo(endpoint) Then
        Exit Sub
      End If

      'ELR: ADDED THIS, to move the startpoint to the start of the line
      'so that the Pad function works correctly
      If Not startpoint.AtStartOfLine Then
      End If

      'IV 2004-12-13: rName = InputBox("Region Name:")
      rName = InputBox("Region Name:", "Pick a name", _

      DTE.UndoContext.Open("Insert A Region")
        junk = startpoint.GetText(startpoint.LineLength)

        pad = String.Empty
        For count = 0 To junk.Length - 1
          If junk.Substring(count, 1).Equals(" ") Or _
          junk.Substring(count, 1).Equals(vbTab) Then
            pad += junk.Substring(count, 1)
            Exit For
          End If

        'ELR: ADDED Test for Languages
        If DTE.ActiveDocument.Language = "CSharp" Then
          ' C Sharp Code
          startpoint.Insert(String.Format("{0}#region {1}{2}", _
            pad, rName, vbCrLf))
          If endpoint.LineLength = 0 Then
            endpoint.Insert(String.Format("{0}#endregion // {1}{2}", _
              pad, rName, vbCrLf))
            endpoint.Insert(String.Format("{0}#endregion // {1}{2}", _
              vbCrLf & pad, rName, vbCrLf))

          End If
          ' VB Code
          startpoint.Insert(String.Format("{0}#Region ""{1}""{2}", _
            pad, rName, vbCrLf))
          If endpoint.LineLength = 0 Then
            endpoint.Insert(String.Format("{0}#End Region '{1}{2}", _
              pad, rName, vbCrLf))
            endpoint.Insert(String.Format("{0}#End Region ' {1}{2}", _
              vbCrLf & pad, rName, vbCrLf))
          End If
        End If
      End Try
    End Sub

    ' IV: Get the description from the 1st line of code in the region
    ' i.e. ignore c# comment tags (///) or take 1st line of the comments (//)
    ' Requires adjustments for VB and other langs
    Private Shared Function GetDesc(ByVal startpoint As EditPoint) As String
      Dim line As String = ""
      Dim tmppoint As EditPoint

      line = startpoint.GetText(startpoint.LineLength)
      If (line.Length > 0) Then
        line = line.TrimStart(" ", vbTab)
        If DTE.ActiveDocument.Language = "CSharp" Then
          If (line.StartsWith("///")) Then
            tmppoint = startpoint
            line = GetDesc(tmppoint)
          ElseIf (line.StartsWith("//")) Then
            line = line.TrimStart("//", " ")
          End If
          line = line.Replace("{", String.Empty)
        End If
        line = line.TrimEnd(" ", vbTab)
      End If
      Return line
    End Function
  End Class

How to use


To install the macro, open up Visual Studio and follow these directions...

  • Open up the Macro Explorer by pressing Alt+F8.
  • Right-click on your MyMacros icon and select "New Module".
  • Give the new module a meaningful name and save it.
  • Right-click on the new module and select "New Macro".
  • Replace "Sub Macro1()" through "End Sub" with the code above.
  • Save the macro file.

Hot Key Assignment

To assign the new MakeRegion macro to Alt+R:

  • In Visual Studio, Click "Tools | Options" from the menu.
  • Open the "Environment" page and select "Keyboard".
  • Click [Save As…] and save the default keyboard mapping with a meaningful name. (You can't modify the default keyboard mapping.)
  • In the "Show Commands Containing:" field, type "MakeRegion".
  • Select the new MakeRegion macro from the list.
  • In the "Use new shortcut in:" field, select "Text Editor".
  • In the "Press shortcut key(s):" field, press "Alt+R".
  • Click the [Assign] button.
  • Click the [OK] button.

You're done! Now, open up the text editor, select some text, and press [Alt+R]. It will take a few seconds to show up the first time it is run. When the dialog pops up, type the name of the region and press Enter.

Happy Regioning!


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Phillip H. Blanton
Architect Hewlett-Packard
United States United States
No Biography provided
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

GeneralStill the best. Pinmemberstano4-Oct-08 18:24 
QuestionWhy not just use Resharper? PinmemberSean Goodpasture17-Oct-06 6:00 
AnswerRe: Why not just use Resharper? PinmemberPhillip H. Blanton17-Oct-06 6:25 
GeneralRe: Why not just use Resharper? PinmemberSean Goodpasture17-Oct-06 6:48 
GeneralRe: Why not just use Resharper? PinmemberPhillip H. Blanton7-Oct-08 12:02 
Generalmodify for the Try Catch.. Pinmembermattmaxx15-Mar-06 6:50 
GeneralAnother macro for region creations PinmemberDan Händevik13-Mar-05 9:01 
Hi, I have posted a new Article describing a few macros for automating code writing. One supports automatic region creation and perhaps can be of assistance to you. Go to[^] and check it out.
Generalsmall request PinmemberNicoRi20-Jan-05 8:27 
GeneralRe: small request PinmemberPhillip H. Blanton11-Dec-05 7:25 
GeneralSmall addition PinmemberRussKie16-Jan-05 20:15 
GeneralNeed to updtae PinmemberArun Manglick4-Jan-05 20:08 
GeneralUpdate Need PinmemberArun Manglick4-Jan-05 20:07 
GeneralUpdate Needed!!! PinmemberPhillip H. Blanton13-Dec-04 13:37 
QuestionLatest macro?? PinmemberMisty_Blue13-Dec-04 7:30 
AnswerRe: Latest macro?? PinmemberRussKie13-Dec-04 12:42 
GeneralRe: Latest macro?? PinmemberPhillip H. Blanton13-Dec-04 13:31 
GeneralLittle variation PinmemberRussKie12-Dec-04 12:39 
GeneralRe: Little variation PinmemberSvenRieke13-Dec-04 0:28 
GeneralStill a problem Pinmembersimonech12-Dec-04 4:28 
GeneralRe: Still a problem Pinmembersimonech12-Dec-04 4:33 
GeneralRe: Still a problem PinmemberPhillip H. Blanton13-Dec-04 12:58 
GeneralLittle bug PinmemberHrusikesh9-Dec-04 9:42 
GeneralRe: Little bug Pinmemberisler-j10-Dec-04 4:30 
GeneralLatest Macro Code PinmemberPhillip H. Blanton8-Dec-04 8:39 
GeneralRe: Latest Macro Code PinmemberPhillip H. Blanton8-Dec-04 8:41 
GeneralVB and C# Fix Pinmemberakku6-Dec-04 13:22 
GeneralRe: VB and C# Fix PinmemberVíctor Sánchez7-Dec-04 4:44 
GeneralRe: VB and C# Fix PinmemberPhillip H. Blanton7-Dec-04 7:40 
GeneralRe: VB and C# Fix PinmemberSergey V. Leshchenko27-May-05 0:28 
GeneralCool... PinsussAnonymous5-Dec-04 7:20 
GeneralRe: Cool... PinmemberPhillip H. Blanton5-Dec-04 15:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150327.1 | Last Updated 3 Jan 2005
Article Copyright 2004 by Phillip H. Blanton
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid