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).
Note
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 Working with 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:
Public Sub AddSomeText() ' Will add code here to add text. End Sub
Declare and initialize a variable to refer to the open code editor.
Dim doc As Document = DTE.ActiveDocument
For more information see Document object and ActiveDocument property.
The Document object contains a TextDocument object, which you can access with the Object method, as shown below.
Dim textDoc As TextDocument = _ CType(doc.Object("TextDocument"), TextDocument)
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.
If doc.ProjectItem.ContainingProject.Kind = _ VSLangProj.PrjKind.prjKindVBProject Then ' Add code here to insert text. End If
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.
textDoc.StartPoint.CreateEditPoint() textDoc.Selection.Insert("' A comment")
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.