如何:控制代码编辑器 (Visual Basic)

Visual Studio 代码编辑器是一个文本编辑器,它可以容纳不同的语言服务,如 Visual Basic、Visual C++ 和 Visual C#。 文本写入文本文档中显示的缓冲区。 使用 Visual Studio 编辑器自动化模型对象,可以在文本缓冲区或视图中幕后操作文本。

用于控制代码编辑器中文本的四个主要对象是:

对象名

说明

TextSelection

用于操作视图中的文本。 TextSelection 对象表示可视文档中的插入点(或插入符号)或选定文本。

TextPoint

文本缓冲区中的固定位置。

EditPoint2

TextPoint 对象类似,但可以移动并且可以修改缓冲区中的文本。

VirtualPoint

TextPoint 对象类似,但包含在虚拟空间中定位文本位置的附加功能。

用于操作代码编辑器的两个主要对象是 TextSelectionEditPoint2 对象。 它们的主要差异是:

  • TextSelection 表示可见的文本选定内容。 更改其位置将更改视图中的选定内容。 EditPoint2 不依赖于任何用户界面 (UI) 组件,因此更改其位置不会更改视图中的任何内容。

  • 因为 TextSelection 表示可见的选定内容,所以每个文档只有一个 TextSelection 对象。 尽管在一个文档中可以有多个 TextSelection 对象,但它们都引用相同的可见选定内容并都有相同的位置。 可以根据需要拥有任意数量的 EditPoint2 对象,并且它们都可以有不同的位置。

  • TextSelection 对象的方法与用户操作存在一一对应关系,但 EditPoint2 的方法不存在这种对应关系。 结果,有些 EditPoint2 方法执行的操作是单个 TextSelection 方法无法执行的,而有些 EditPoint2 方法在功能上比 TextSelection 方法更完整。 这也是 TextSelection 在属性和方法上比 EditPoint2 更丰富的原因。

使用这些对象,可以:

  • 选择、添加、删除和移动缓冲区或视图中的文本。

  • 在缓冲区或视图中四处移动插入点。

  • 缩进缓冲区或视图中的文本。

  • 插入、移除和定位到书签。

  • 添加或移除文本(包括空格)。

  • 基于指定模式查找或替换文本。

  • 创建代码和文本中的大纲部分。

  • 查询有关文本的信息(如文本位置、文档的顶部和底部、选定的文本范围等)。

下面的宏示例演示如何引用和使用编辑器自动化模型的各种成员。 有关如何运行代码示例的更多信息,请参见 如何:编译和运行自动化对象模型代码示例

有关演示编辑器自动化模型用法的其他示例,请参见 Automation Samples for Visual Studio (https://msdn2.microsoft.com/en-us/vstudio/aa718336.aspx)(Visual Studio 自动化示例)网站上的“拼写检查”宏和其他示例。

提示

显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您当前的设置或版本。这些过程是使用当前的常规开发设置开发的。 若要更改设置,请在“工具”菜单上选择“导入和导出设置”。 有关更多信息,请参见 使用设置

随着 Visual Studio 2008 HTML 编辑器中“拆分”视图的引入,增加了 HTMLWindow3vsHTMLPanesvsHTMLViews。 “拆分”视图将 HTML 编辑器窗口的选项卡和视图元素分隔开来。 切换视图(到“设计”或“源”视图)并不一定意味着切换选项卡(“设计”/“拆分”/“源”)。 例如,当您单击“拆分”选项卡时,在“设计”和“源”之间切换视图不会更改选项卡,而只会在“拆分”视图中激活或取消激活“设计”和“源”部分。

示例

ActivePoint 的宏示例。 本示例还演示 StartOfLineDisplayColumnEndOfLine 的用法。 运行此示例之前,请先在 Visual Studio 中打开代码文件或文本文档,再向其添加某些文本并选择部分文本。

' Macro example for TextSelection.ActivePoint.
'
Sub ActivePointExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection
    Dim objActive As VirtualPoint = objSel.ActivePoint
     ' Collapse the selection to the beginning of the line.
    objSel.StartOfLine()
     ' objActive is "live", tied to the position of the actual 
     ' selection, so it will reflect the new position.
    Dim iCol As Long = objActive.DisplayColumn
     ' Move the selection to the end of the line.
        objSel.EndOfLine()

    MsgBox("The length of the insertion point line is " & _
    (objActive.DisplayColumn - iCol) & " display characters.")
End Sub

AnchorPoint 的宏示例。 本示例还演示 DisplayColumnLineStartOfDocumentEndOfDocument 的用法。 运行此示例之前,请先在 Visual Studio 中打开代码文件或文本文档,再向其添加某些文本并选择部分文本。

' Macro example for TextSelection.AnchorPoint.
'
Sub AnchorPointExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection
    Dim objAnchor As VirtualPoint = objSel.AnchorPoint
    ' objAnchor is "live", tied to the position of the actual 
    ' selection, so it will reflect changes. iCol and iRow are created 
    ' here to save a "snapshot" of the anchor point's position at this 
    ' time.
    Dim iCol As Long = objAnchor.DisplayColumn
    Dim iRow As Long = objAnchor.Line
    ' As the selection is extended, the active point moves but the 
    ' anchor point remains in place.
    objSel.StartOfDocument(True)
    objSel.EndOfDocument(True)

    If (iCol = objAnchor.DisplayColumn And iRow = objAnchor.Line) Then
        MsgBox("The anchor point has remained in place at row " & _
        iRow & ", display column " & iCol)
    End If
End Sub

Insert 的宏示例。 本示例还演示 IsEmptyWordLeftWordRightTextDeleteMoveToPoint 的用法。 运行此示例之前,请先在 Visual Studio 中打开代码文件或文本文档,并在其中添加某些文本。

' Macro example for TextSelection.Insert.
'
Sub InsertExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection
    If objSel.IsEmpty Then
        ' If there is no text selected, swap the words before and after 
        ' the insertion point. We begin by selecting the word before 
        ' the insertion point.
        objSel.WordLeft(True)
        If Not objSel.IsEmpty Then
            ' We can continue only if the selection was not already at 
            ' the beginning of the document.
            Dim strBefore As String = objSel.Text

            ' The text is saved in strBefore; now delete it and move 
            ' past the following word.
            objSel.Delete()
            objSel.WordRight(True)
            If objSel.Text.StartsWith(" ") Or _
            objSel.Text.StartsWith(Microsoft.VisualBasic. _
            ControlChars.Tab) Then
                ' The previous call to WordRight may have skipped some 
                ' white space instead of an actual word. In that case, 
                 ' we should call it again.
                objSel.WordRight(True)
            End If

            ' Insert the new text at the end of the selection.
            objSel.Insert(strBefore, _
            vsInsertFlags.vsInsertFlagsInsertAtEnd)
        End If
    Else
        ' If some text is selected, replace the following word with the 
        ' selected text.
        Dim strSelected As String = objSel.Text

        objSel.MoveToPoint(objSel.BottomPoint)
        objSel.WordRight(True)
        If objSel.Text.StartsWith(" ") Or _
        objSel.Text.StartsWith(Microsoft.VisualBasic. _
        ControlChars.Tab) Then
            ' The previous call to WordRight may have skipped some 
            ' white space instead of an actual word. In that case, we 
            ' should call it again.
            objSel.WordRight(True)
        End If

        ' Insert the text, overwriting the existing text and leaving 
        ' the selection containing the inserted text.
        objSel.Insert(strSelected, _
        vsInsertFlags.vsInsertFlagsContainNewText)
    End If
End Sub

FindPattern 的宏示例。 本示例还演示 SelectLine 的用法。 运行此示例之前,需要在 Visual Studio 中打开文本文档或代码文件,并在其中添加某些文本。

' Macro example for TextSelection.FindPattern.
'
Sub FindPatternExample()
    ' Before running this example, open a text document.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection

    ' Advance to the next Visual Basic function beginning or end by 
    ' searching for  "Sub" with white space before and after it.
    If objSel.FindPattern(":WhSub:Wh", _
    vsFindOptions.vsFindOptionsRegularExpression) Then
        ' Select the entire line.
        objSel.SelectLine()
    End If
End Sub

OutlineSection 的宏示例。 本示例还演示 StartOfDocumentLineLineCharOffsetFindPatternSwapAnchorMoveToLineAndOffsetLineDown 的用法。 运行此示例之前,请先在 Visual Studio 中打开包含 #if _DEBUG…#endif 块的代码文档。

' Macro example for TextSelection.OutlineSection.
'
Sub OutlineSectionExample()
    ' Before running this example, open a code document
    ' containing a #if _DEBUG…#endif block.
    Dim objSel As TextSelection = DTE.ActiveDocument.Selection

    ' Move to the beginning of the document so we can iterate over the 
    ' whole thing.
    objSel.StartOfDocument()
    While objSel.FindPattern("#if _DEBUG")
        ' If we found the beginning of a debug-only section, save the 
        ' position.
        Dim lStartLine As Long = objSel.TopPoint.Line
        Dim lStartColumn As Long = objSel.TopPoint.LineCharOffset

        ' Look for the end.
        If objSel.FindPattern("#endif") Then
            ' Select the entire section and outline it.
            objSel.SwapAnchor()
            objSel.MoveToLineAndOffset(lStartLine, lStartColumn, True)
            objSel.OutlineSection()
            objSel.LineDown()
        End If
    End While
End Sub

宏示例打开一个文本文档并将所有可用命令列表生成到该文档。

' Macro example
  ' This generates a text document listing all available command names.
Sub CommandNamesCollapseExample()
  Dim Cmd As Command
  Dim Commands As Commands = DTE.Commands 
  Dim PrjItem As ProjectItem
  Dim Doc As Document
  Dim TxtDoc As TextDocument
  DTE.ItemOperations.NewFile ("General\Text File")
  Set Doc = ActiveDocument
  Set TxtDoc = Doc.Object("TextDocument")
  For Each Cmd In Commands
  If (Cmd.Name <> "") Then
    TxtDoc.Selection.Text = Cmd.Name & vbLF
    TxtDoc.Selection.Collapse
  End If
  Next
End Sub

HTMLWindow 对象的宏示例。 本示例还演示 ActiveDocumentActiveWindowWindowCurrentTabCurrentTabObjectActivePaneStartPointCreateEditPointFindPatternInsertFromFile 的用法。 运行此示例之前,请先在 Visual Studio 中打开一个 HTML 文档。

' Macro example for HTMLWindow object

Sub HTMLWindowExample()
   ' Open an HTML document before running this sample.
   If TypeOf ActiveDocument.ActiveWindow.Object Is HTMLWindow Then
      ' Ask the user for a file to insert into the body of the HTML 
      ' document. This file should be an HTML fragment.
      Dim strFile As String = InputBox("Enter the name of a file to _
      insert at the end of the HTML document:")
      ' Get the HTMLWindow object and determin which tab is currently 
      ' active.
      Dim objHTMLWin As HTMLWindow = ActiveDocument.ActiveWindow.Object
      Dim Tab As vsHTMLTabs = objHTMLWin.CurrentTab

      ' Switch to the "source" tab.
      objHTMLWin.CurrentTab = vsHTMLTabs.vsHTMLTabsSource

      ' Get an EditPoint at the start of the text.
      Dim objTextWin As TextWindow = objHTMLWin.CurrentTabObject
      Dim objEP As EditPoint = _
      objTextWin.ActivePane.StartPoint.CreateEditPoint

      ' Look for the end of the document body.
      If objEP.FindPattern("</body>") Then
         ' Insert the contents of the file.
         objEP.InsertFromFile(strFile)
      End If

      ' Switch back to the original view of the HTML file.
       objHTMLWin.CurrentTab = Tab
   Else
      MsgBox("You must open an HTML document.")
   End If
End Sub

请参见

任务

如何:更改窗口特性

如何:创建外接程序

演练:创建向导

概念

自动化对象模型图表

其他资源

创建和控制环境窗口

创建外接程序和向导

自动化与扩展性参考