Export (0) Print
Expand All

Using a Macro to Add Text in a Visual Basic or Visual C# Code Editor

Visual Studio .NET 2003

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.

Note   The following steps will create add text to a Visual Basic code editor. To add code to a C# code editor, use the
prjKindCSharpProject
enumeration value in step 5.

To add text at the top of the active Visual Basic code editor

  1. Create a new macro module named EditorMacros.
  2. 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
    
  3. Declare and initialize a variable to refer to the open code editor. For more information see Document Object and ActiveDocument Property (DTE Object).
    Dim doc As Document = DTE.ActiveDocument
    
  4. The Document object contains a TextDocument object, which you can access with the Object method.
    Dim textDoc As TextDocument = _
       CType(doc.Object("TextDocument"), TextDocument)
    
  5. 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
    
  6. Using the TextDocument object, you can 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 (General Extensibility) and Selection Property (General Extensibility).
    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
    
  7. Save the macro, close the Macros IDE, and run the macro from the Macro Explorer.

See Also

ActiveDocument Property (DTE Object) | Document Object | TextDocument Object | CreateEditPoint Method (General Extensibility) | Selection Property (General Extensibility)

Show:
© 2015 Microsoft