Click here to Skip to main content
15,354,956 members
Articles / Programming Languages / Visual Basic
Posted 13 Mar 2005


162 bookmarked

Automating the code writing process using macros

Rate me:
Please Sign up or sign in to vote.
4.63/5 (33 votes)
5 Jul 2007CPOL11 min read
This article describes the documentator macros for making code writing with Visual Studio 2003 a lot faster and easier.


See history for a full changelog. The documentation found in the zip contains an updated documentation in addition to the changelog of the macros.


When writing code and documentation for source files, there is much manual work to complete the task. Often you follow a specific code standard and some code you write quite often with small changes. I have developed a set of macros for easing my daily work and thus making me more efficient as a developer. These macros employ our company's code standard, that hopefully are not so far from yours, and they can be fine-tuned to match your standards.

The macros focus on inline XML documentation, region blocks, automation and refactoring. They work with Visual Studio 2003 and primarily with C#, but some macros also support VB.NET.


Download the supplied files and follow the instructions given below:

For VS 2005

  1. Open the Macro explorer (Alt+F8 or View -> Other windows -> Macro Explorer)
  2. Rightclick "Macros" in the macro explorer and select "Load Macro Project"
  3. Select the "Meridium.vsmacros" and click "Add"
  4. Run the Macro Meridium.Documentator.FixKeyMapping to install the shortcuts
  5. [Optional] If you have installed the Resharper add-in, run the Meridium.Documentator.FixKeyMappingsAfterResharperInstallation macro
  6. Ready to go

For VS 2003

  1. Create a new keyboard mapping scheme if you are using the Default settings (Tools -> Options -> Environment-> Keyboard-> Save as)
  2. Load the macro project "Meridium.vsmacros" in Visual Studio (Tools -> Macros -> Load Macro project...)
  3. Open the Macro explorer (Alt+F8 or Tools -> Macros -> Macro Explorer)
  4. Run the Macro Meridium.Documentator.FixKeyMapping to install the shortcuts
  5. Ready to go

Using the macros

The full explanation of the macros exists in the manual, but I will give some descriptions for the main features.

For instance, if you have written a method that looks like this:

public int MyMethod(string name, int maxNo, Font font) 
    //my code

and then invoke the Document and regionize macro (Ctrl+d), you'll end up as follows:

#region public int MyMethod(string name, int maxNo, Font font)
/// <summary>
/// </summary>
/// <param name="name"></param>
/// <param name="maxNo"></param>
/// <param name="font"></param>
/// <returns></returns>
public int MyMethod(string name, int maxNo, Font font) 
    //my code

The cursor is then placed at the first XML doc tag (<summary>) and you are ready to start documenting. If you have also activated the EnableTabMapping, you can use Tab and Shift+Tab to move between the different tags in the XML doc section.

It also supports updates, so if you add a parameter or change the order of the parameters and then activate the macro again, the documentation and region will be updated.

Another major macro is the PasteTemplate macro that supports automation and refactoring by templates. For now, the templates are hard coded into the macros, but you can easily modify them to suit your own needs.

For example, if you want to create a try catch clause, enter the following text:


and activate the PasteTemplate macro (Ctrl+J), you'll end up as follows:

catch(Exception ex) 

More automation functions exists. Try fori, trycm, trycf, tryf, gp, sp and gsp.

A more complex automation is supported when creating events. If you define the following event:

public event EventHandler MyEvent;

and activate the PasteTemplate macro, you'll end up with the following code:

#region public event EventHandler MyEvent
/// <summary>
/// This event is fired when
/// </summary>
public event EventHandler MyEvent;
#region protected virtual void OnMyEvent(EventArgs e)
/// <summary>
/// Notifies the listeners of the MyEvent event
/// </summary>
/// <param name="e">The argument to send to the
protected virtual void OnMyEvent(EventArgs e) 
    if(MyEvent != null) 

This saves a lot of time.

The same macro also adds refactoring capabilities. For instance, if you want to convert a field to a property,

public string Name;

place the cursor at the end of the line and activate the PasteTemplate macro, you'll end up as follows:

public string Name;
    get { return _name; }
    set { _name = value; }
private string _name;

Then add the Document and regionize macro to that, and in a few seconds, you have refactored and documented your field.

The field refactoring method contains a few variants depending on the field initialization; look in the manual for a full description. I have added some more refactoring types, but you'll have to look in the manual for the complete specification.

Given below are some macros described in short, a full description exists in (yes, you are right) the manual.


Document and regionize this

Ctrl + dAdds updates to the XML documentation on the current code element and puts #region #endregion directives around the section.

Paste template

Ctrl + Shift+ jChecks for keywords and pastes an appropriate template. Compare to Borland's template functions and VS 2005 Code Snippets.

Toggle parent region

Ctrl + m, Ctrl + mToggles the parent #region block.

Expand all regions

Ctrl + Shift + +Expands all #region blocks.

Collapse all regions

Ctrl + Shift + -Collapses all #region blocks.

Create documentation heading

Ctrl + Shift + Alt + hCreates a Documentation heading.

Format current document

Ctrl + Shift + dFormats the current document, compare to Edit.FormatSection.

Sort lines ascending

Ctrl + Alt + sSorts the selected lines in an ascending order.
Sort lines descendingCtrl + Alt + Shift + sSorts the selected lines in a descending order.

Install documentation toolbar items

Installs user configured toolbar(s) and items in the toolbox.

Act on tab

Ctrl + <Advances to the next XML doc tag if cursor is in an XML doc block.

Act on shift tab

Ctrl + >Goes to the previous XML doc tag if cursor is in an XML doc block.

Fix key mappings

Connects all shortcuts to the macros, except the Act on tab and Act on shift tab macros.
Remove key mappingsRemoves all keymappings for the Macros. (Doesn't restore any overridden macros though)
Fix key mappings after resharper installationFixes some keymapping collisions between resharper, DocumentatorMacros and VisualStudio.
MakeCDataWraps the selected text in a <![CDATA[ ... ]]> structure.
FixHTMLValidationErrorsFixes common validation errors in HTML documents.
KillLineCtrl + Shift + kKills the rest of the line
EnterCodeCommentCtrl + Shift + cCreates a comment on the format <date>: <domain>\<user>
EnterCodeRemarkCtrl + Shift + Alt + cAppends a remark comment to the current class documentation
RemoveWordPasteHtmlTagsRemoves Word specific HTML tags and attributes if you paste some formatted text from Word.
HTMLEncodeHTML encodes the marked text

Auto documentation

For properties, indexers and some methods, a default documentation is provided when the Document(AndRegionize) macro is invoked.

The following elements are auto documentated:

Method/Element Example

Initializes a new instance of the <b>MyType</b> class.


Releases unmanaged resources and performs other cleanup operations before
the <b>MyType</b> is reclaimed by garbage collection.

void Dispose(...)

Releases the resources used by the <b>MyType</b>

string ToString(...)<summary>
Returns a <see cref="String"/>that represents the current <see cref="MyType"/>.
<returns>A <see cref="String"/> that represents the current <see cref="MyType"/>.</returns>
bool Equals(MyType o)<summary>
Determines whether the specified <see cref="MyType"/> is equal to the current
<param name="o">The <see cref="MyType"/> to compare with the current <see cref="MyType"/>.</param>
<returns>true if the specified <see cref="MyType"/> is equal to the current <b>MyType</b>.;
otherwise, false.</returns>
bool Equals(MyType a, MyType b)<summary>
Determines whether the specified <see cref="MyType"/> instances are considered equal.
<param name="a">The first <see cref="MyType"/> to compare</param>
<param name="b">The second <see cref="MyType"/> to compare</param>
<returns> true if <i>a</i> is the same instance as <i>a</i>
or if both are null references or if <c>a.Equals(b)</c> returns true; otherwise, false. </returns>
int GetHashCode(...)<summary>
Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.
<returns>A hash code for the current <see cref="MyType"/>.</returns>

[Get/Set]s the [PropertyName] of the [ClassType]


[Get/Set]s <see cref="[IndexerType]"/> item identified by the given arguments of the [ClassType]

void ControlName_EventName(object param1, [Any]Args param2)

This method is called when the [ControlName]'s [eventName] event has been fired.
<param name="param1">The <see cref="object"/> that fired the event</param><param name="param2">The <see cref="AnyArgs"/> of the event</param>

Clone(Object obj)

Creates a new object that is a copy of the current instance.
<param name="source"></param>
<returns>A new object that is a copy of this instance.</returns>
bool Contains(Object obj)<summary>
Returns a value indicating whether the specified <see cref="Object"/>is contained in the <see cref="Class1"/>.
<param name="a">The <see cref="Object"/> to locate in the
<see cref="Class1"/></param>
<returns><b>true</b> if the <i>Object</i> parameter is a member
of the <see cref="Class1"/>; otherwise, <b>false</b>.</returns>
bool IsWord(..)<returns>True if it is word, otherwise false.</returns>
bool IsWord1Word2WordN(...)<returns>True if word1 word2 is wordn, otherwise false.</returns>
[Any]Format(string format, param object[] args)<param name="format">A string containing zero or more format specifications.</param>
<param name="args">An array of objects to format.</param>
int Compare(MyType x, MyType y)<summary>Compares two objects and returns a value indicating whether one is less than,
equal to, or greater than the other.<summary>
<param name="x">The first object to compare.</param><param name="y">The second object to compare.</param>
<returns>A 32-bit signed integer that indicates the relative order
of the objects being compared. The return value has these meanings:
Less than zerox less than y.
Zerox is equal to y.
Greater than zero x is greater than y.
int CompareTo(MyType o)<summary>Compares the current instance with another object of the same type.</summary>
<param name="o">The <see cref="MyType"> to compare with this instance.</param>
<returns>A 32-bit signed integer that indicates the relative order
of the objects being compared. The return value has these meanings:
Less than zeroThis instance is less than 0.
ZeroThis instance is equal to 0.
Greater than zeroThis instance is greater than 0.

Points of Interest

I have to thank Roland Weigelt for his inspiring GhostDoc and some other macros (region expand). The Key mapping binder is also found on the net, I can't remember where though.

The upcoming Visual Studio 2005 will be a good update for the automation and refactoring with the introduction of code snippets.


2007-06-28 -

Contains support for

  • New macros

    • FixKeyMappingsAfterReSharper25Installation - renamed from FixKeyMappingsAfterReSharperInstallation. Used to setup keymappings after Resharper 2.5 has been installed
    • FixKeyMappingsAfterResharper3Installation - Used to setup keymappings after Resharper 3 has been installed
    • KillHtmlStyleAndClassFormatting - removes style and class formatting from selected HTML code

  • Enhancements /Bugfixes

    • PasteTemplate - added the disp keyword
    • EnterCodeRemark - Better output of code remarks
    • RemoveWordPasteHtmlTags - removes all mso-* styles, lang attributes from span tags.
    • DocumentThis - Auto documents public void Dispose(bool disposing)

007-01-25 -

Version is a branch from v that supports Visual Studio 2003. The 2003 branch misses all additional functionality after version and has to be developed separately. I have no intention (personal need) to bring the 2003 branch up to the same functionality as the 2005 branch but if you feel like implementing in the 2003 branch, please send me your modifications and I can update this project.

  • New macros

    • FixKeyMappingsAfterResharper203Installation - updates the keyboard shortcuts

2007-01-15 -

  • Supports Visual Studio 2005 and

  • New macros

    • KillLine - Kills the rest of the line
    • EnterCodeComment - Enters a code comment on the format <date>: <domain>\<user>
    • EnterCodeRemark - Appends a remark comment to the current class documentation
    • RemoveWordPasteHtmlTags - Removes Word specific HTML tags and attributes if you paste some formatted text from Word.
    • HTMLEncode - HTML encodes the marked text

  • Enhancements/Bugfixes

    • FixKeyMappingsAfterResharperInstallation - Supports Resharper 2.5
    • CollapseAllRegions - now supports nested regions (thanks to DragonWang_SFIS) and commented ones.
    • PasteTemplate
      • Indentions now work better.
      • PropertyChanged events now fully documented
      • Field to property now recognizes private _variables and converts them to public Properties
      • for to foreach matches better
    • MakeCData - now does not HTML encode the selected text before creating the CData section.
    • FixHTMLValidationErrors
      • Combines multiple style attributes
      • Removes language and ms_positioning attributes from div tags
      • Removes topmargin attributes from body tags
      • Adds alt attributes to images if missing (defaults to the same as src)
    • DocumentThis
      • Better support for generics
      • Now supports explicit generic interfaces
      • Autodocuments [Any]Format(string format, param object[] args) methods
      • Autodocuments Compare methods
      • Regionizes better on long declarations
  • Updated installation instructions

2006-02-27 -

  • Supports Visual Studio 2005. For VS2003 support please use version

  • New macros

    • MakeCData
    • Fix HtmlValidationErrors

  • Enhancements/Bugfixes

    • FixKeyMappingsAfterResharperInstallation - Supports
    • DocumentAndRegionizeThis - now works with VB.NET
  • CommentSection - Macro removed (VS 2005 internal CommentSection now works with XML/HTML/Javascript code
  • Plus an additional lot of enhancements and bugfixes

2005-10-27 -

  • Even more functions and enhancements

  • New macros

    • LoadColorableSettings
    • SaveColorableSettings
    • FixKeyMappingsAfterReSharperInstallation

  • Enhancements/Bugfixes

    • PasteSeeParameterXmlDocTag
      • Now works with delegates, Structs, Interfaces, Namespaces
    • DocumentAndRegionize
      • Added autodocumentation features on
        • get/set properties
        • indexers (interface)
        • "Is" methods

2005-06-08 -

  • Some more functions and enhancements.
  • Now more compatible with ReSharper

  • New Macros

    • PasteSeeParameterXmlDocTag
    • DocumentThis
    • RemoveKeyMappings

  • Enhancements/Bugfixes

    • DocumentAndRegionize
      • Added autodocumentation features on
        • Properties
        • Indexers
        • Event methods
        • Clone methods
        • Contains methods
    • PasteTemplate
      • Changed shortcut to Ctrl + Shift + j (to work with ReSharper)
      • fori template changed
      • Added templates forj, fork, test
    • ActOnTab
      • Changed shortcut to Ctrl + < (didn't want to lock up the tab key any longer)
    • ActOnShiftTab
      • Changed shortcut to Ctrl + > (didn't want to lock up the tab key any longer)
  • EnableTabMappings - Removed
  • DisableTabMappings - Removed

2005-04-07 -

  • This release contains a few more functions and bugfixes

  • Enhancements/Bugfixes

    • PasteTemplate
      • Added Singleton Template in PasteTemplate
      • Convert to property now recognizes static properties
    • DocumentAndRegionize
      • Document and Regionize now actually fills in documentation for a few methods
      • Empty documentation tags are now removed
      • Now Documents classes (not regionizes them)
      • Regionizes variables in structs
      • Better general quality of output XML documentation
      • Don't add <return> tags on properties anymore
      • Adds <value> tags on properties
      • Basic XML documentation now functions correctly when using this macro several times
      • No longer divides single tags into start/end tags when not appropriate

2005-03-15 -

  • Removed the reference to Se.MeridiumKalmar (thanks enigmacs).

2005-03-13 -

  • First public release


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


About the Author

Dan Handevik
Web Developer
Sweden Sweden
Dan Händevik is a software architect/developer, employed at Meridium ( ) as Director of Development.
Dan has been programming since late 1980:s and is skilled in several programming languages such as C#, Java, Perl, VB.Net, JavaScript, VBScript and much more.
On his spare time, he enjoys spending time with his family and children.
Visit his blog for more information

Comments and Discussions

QuestionDo you have any for Pin
Prasenjit Purohit14-Apr-09 20:24
MemberPrasenjit Purohit14-Apr-09 20:24 
AnswerRe: Do you have any for Pin
Dan Handevik19-Apr-09 20:29
MemberDan Handevik19-Apr-09 20:29 
QuestionIs it applicable/will it work in VS2008? Pin
Bill Seddon28-Feb-08 21:53
MemberBill Seddon28-Feb-08 21:53 
AnswerRe: Is it applicable/will it work in VS2008? Pin
Dan Handevik28-Feb-08 23:31
MemberDan Handevik28-Feb-08 23:31 
QuestionHow to disable a macro? Pin
anisa_allahdadi7-Sep-07 22:08
Memberanisa_allahdadi7-Sep-07 22:08 
AnswerRe: How to disable a macro? Pin
Dan Handevik9-Sep-07 8:21
MemberDan Handevik9-Sep-07 8:21 
Questionctrl + d is nice, but how about doing that for a awhole project or solution? Pin
Relampago28-Jun-07 20:11
MemberRelampago28-Jun-07 20:11 
AnswerRe: ctrl + d is nice, but how about doing that for a awhole project or solution? Pin
Dan Handevik28-Jun-07 20:39
MemberDan Handevik28-Jun-07 20:39 
QuestionCreate a Form and open the Designer Pin
Paolo Pagano6-Feb-07 21:18
MemberPaolo Pagano6-Feb-07 21:18 
GeneralA working ExpandAllRegions Pin
mjwills6-Sep-06 16:01
Membermjwills6-Sep-06 16:01 
GeneralRe: A working ExpandAllRegions Pin
Dan Handevik7-Jan-07 21:15
MemberDan Handevik7-Jan-07 21:15 
QuestionNew node in header Pin
lpastor23-Aug-06 2:54
Memberlpastor23-Aug-06 2:54 
AnswerRe: New node in header Pin
Dan Handevik24-Aug-06 0:28
MemberDan Handevik24-Aug-06 0:28 
GeneralRe: New node in header Pin
lpastor25-Aug-06 2:46
Memberlpastor25-Aug-06 2:46 
GeneralRe: New node in header Pin
Dan Handevik25-Aug-06 11:43
MemberDan Handevik25-Aug-06 11:43 
GeneralSome changes for CollapseAllRegions Pin
Darrell Wang16-May-06 20:53
MemberDarrell Wang16-May-06 20:53 
AnswerRe: Some changes for CollapseAllRegions Pin
Dan Handevik17-May-06 23:40
MemberDan Handevik17-May-06 23:40 
QuestionMacros in C# Pin
CodeIsGod15-May-06 20:29
MemberCodeIsGod15-May-06 20:29 
AnswerRe: Macros in C# Pin
Dan Handevik15-May-06 21:34
MemberDan Handevik15-May-06 21:34 
GeneralKeyboard Pin
u neek9-Mar-06 11:02
Memberu neek9-Mar-06 11:02 
AnswerRe: Keyboard Pin
Dan Handevik10-Mar-06 1:52
MemberDan Handevik10-Mar-06 1:52 
GeneralRe: Keyboard Pin
u neek10-Mar-06 6:19
Memberu neek10-Mar-06 6:19 
AnswerRe: Keyboard Pin
Dan Handevik11-Mar-06 19:19
MemberDan Handevik11-Mar-06 19:19 
GeneralSweet! Pin
mashiharu27-Feb-06 22:55
Membermashiharu27-Feb-06 22:55 
GeneralSmall note on your .chm file Pin
cbono20001-Nov-05 11:12
Membercbono20001-Nov-05 11:12 

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

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