How to: Use a Macro to Add Text in a Visual Basic, C# or J# Code Editor
You can use the extensibility object model to add code to any Visual Basic or Visual C# or Visual J# 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. 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 theenumeration value in step five (5). To add code to a Visual J# code editor, use the 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.
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.
For more information seeobject and property.
The Document object contains aobject, which you can access with the Object method, as shown below.
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 theproperty to add text to the editor. For more information see 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.