Auto-Insert Error Handling Macro In VB.Net
Here's how to bind a key combination to a macro which will automatically insert your error handling, or other frequently inserted text into your VB.Net code for you. This example is in Visual Studio 2003, but it'll probably be similar in newer versions of Visual Studio.
First, Add The Macro
Open the Macro Explorer
The Macro Explorer tree view will appear. Double click on Module1, and the Macro Editor will appear.
The following macro will add the default Try, Catch etc, re-indent the new function, and position the cursor ready for your typing. Add the following function within the Module1 module:
Sub addEventHandling() Dim ts As TextSelection = DTE.ActiveDocument.Selection Dim s As String s &= " Try" & vbNewLine s &= " Me.Cursor = Cursors.WaitCursor" & vbNewLine s &= "" & vbNewLine s &= "" & vbNewLine s &= "" & vbNewLine s &= " Catch ex As Exception" & vbNewLine s &= " m_errors.handle(ex)" & vbNewLine s &= "" & vbNewLine s &= " Finally" & vbNewLine s &= " Me.Cursor = Cursors.Default" & vbNewLine s &= "" & vbNewLine s &= " End Try" & vbNewLine ts.EndOfLine() ts.NewLine() ts.Insert(s) DTE.ActiveDocument.Selection.LineUp(False, 9) DTE.ExecuteCommand("Edit.FormatDocument", "") DTE.ActiveDocument.Selection.Indent(3) End Sub
Now To Bind A Key Combination
Now save the macro, and return to your project. Go to Tools -> Options. Select Keyboard from the tree view. In the box labeled Show Commands Containing, enter addEventHandling. Click your new macro which should show in the box below, and click the cursor in the Press Shortcut Keys box. Press your desired key combination. I have used Ctrl+N, which is normally assigned to New Document.
That's it. To use the macro, you just have to hit Ctrl+N from your Code Window. Couble-click a button or another control on your form to enter the code for its click event, and hit Ctrl+N. Hey presto!
Saves me loads of typing anyway...