Share via


HOW TO:控制程式碼編輯器 (Visual Basic)

Visual Studio 程式碼編輯器是一個提供了 Visual Basic、Visual C++ 和 Visual C# 等語言服務的文字編輯器。 文字會寫入在文字文件中顯示的緩衝區。 使用 Visual Studio 編輯器 Automation 模型物件,就可以在文字緩衝區或檢視中幕後操作文字。

程式碼編輯器中用來控制文字的四個主要物件如下:

物件名稱

描述

TextSelection

用於在檢視中操作文字。 TextSelection 物件表示可見文件中的插入點 (或插入號) 或選取文字。

TextPoint

文字緩衝區中的固定位置。

EditPoint2

類似於 TextPoint 物件,但是可以移動,也可以在緩衝區中修改文字。

VirtualPoint

類似於 TextPoint 物件,不同的是它包含了其他功能,可以在虛擬空間中找出文字位置。

用來操作程式碼編輯器的兩個主要物件為 TextSelectionEditPoint2 物件。 兩者之間主要差異如下:

  • TextSelection 表示可見的文字選取範圍。 變更其位置會變更檢視中的選取範圍。 EditPoint2 並未連結至任何使用者介面 (UI) 元件,因此變更其位置不會變更檢視中的任何內容。

  • 由於 TextSelection 表示可見的選取範圍,因此每份文件只有一個 TextSelection 物件。 雖然一份文件中可以有多個 TextSelection 物件,但是所有物件都參考同一個可見的選取範圍,而且位置都相同。 反之,您可以依照需要擁有任意多個 EditPoint2 物件,而且所有物件的位置都可以不同。

  • TextSelection 物件的方法設計為與使用者動作具有一對一對應關係,但是 EditPoint2 物件的方法則非如此。 因此,有些 EditPoint2 方法可執行 TextSelection 方法無法執行的動作,有些 EditPoint2 方法的功能比 TextSelection 方法更細微。 這也是 TextSelection 的屬性和方法比 EditPoint2 更豐富的原因。

使用這些物件,您可以:

  • 選取、加入、刪除及移動緩衝區或檢視中的文字。

  • 移動緩衝區或檢視四周的插入點。

  • 縮排緩衝區或檢視中的文字。

  • 插入、移除及巡覽書籤。

  • 加入或移除文字,包括空白字元。

  • 根據指定的模式尋找或取代文字。

  • 在程式碼和文字中建立大綱區段。

  • 查詢文字的相關資訊,例如文字位置、文件的頂部和底部、選取的文字範圍等。

在下列巨集範例中,會示範如何參考及使用編輯器 Automation 模型的各個成員。 如需如何執行範例程式碼的詳細資訊,請參閱 HOW TO:編譯和執行 Automation 物件模型程式碼範例

如需示範如何使用編輯器 Automation 模型的其他範例,請參閱 Visual Studio Automation 範例 (https://msdn2.microsoft.com/en-us/vstudio/aa718336.aspx) 網站 (英文) 上的<Spell Check Macro>和其他範例。

注意事項注意事項

根據目前使用的設定與版本,您所看到的對話方塊與功能表命令可能會與 [說明] 中所描述的不同。這些程序已使用現行的 [一般開發設定] 進行開發。 若要變更設定,請從 [工具] 功能表中選擇 [匯入和匯出設定]。 如需詳細資訊,請參閱 使用設定

在 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

請參閱

工作

HOW TO:變更視窗特性

HOW TO:建立增益集

逐步解說:建立精靈

概念

Automation 物件模型圖表

其他資源

建立和控制環境視窗

建立增益集和精靈

Automation 與擴充性參考