|Important||This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.|
How to: Use a Macro to Add Text in a Visual Basic or C# Code Editor
You can use the extensibility object model to add code to any Visual Basic or Visual C# code editor. Possible uses of this feature include adding new procedures and adding standard comment blocks. This task assumes that you know how to access the Macros development environment and create a macro project. For more information, see Add Macro Project Dialog Box. To implement the following macro sample, you need to have a Visual Basic project open.
The following steps add text to a Visual Basic code editor. To add code to a Visual C# code editor, use the prjKindCSharpProject enumeration value in step five (5).
The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. These procedures were developed with the General Development Settings active. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Visual Studio Settings.
To add text at the top of the active Visual Basic code editor
Create a new macro module named EditorMacros.
Create a new macro, AddSomeText, by adding the following code to the macro module:
Declare and initialize a variable to refer to the open code editor.
To make sure that you are adding code to the Visual Basic code editor, you can test the Kind property of the project that contains the window.
Using the TextDocument object, create an editing point at the beginning of the editor. Then use the Insert method of the Selection property to add text to the editor. For more information see CreateEditPoint method and Selection property.
The complete macro appears below:
Public Sub AddSomeText() Dim doc As Document = DTE.ActiveDocument Dim textDoc As TextDocument = _ CType(doc.Object("TextDocument"), TextDocument) If doc.ProjectItem.ContainingProject.Kind = _ VSLangProj.PrjKind.prjKindVBProject Then textDoc.StartPoint.CreateEditPoint() textDoc.Selection.Insert("' A comment") End If End Sub
Save the macro, close the Macros IDE, and run the macro from Macro Explorer.