TextPattern.GetSelection 方法


检索与当前文本选择(或多个文本选择)关联的不连续文本范围的集合。Retrieves a collection of disjoint text ranges associated with the current text selection or selections.

 cli::array <System::Windows::Automation::Text::TextPatternRange ^> ^ GetSelection();
public System.Windows.Automation.Text.TextPatternRange[] GetSelection ();
member this.GetSelection : unit -> System.Windows.Automation.Text.TextPatternRange[]
Public Function GetSelection () As TextPatternRange()


不连续文本范围的集合。A collection of disjoint text ranges.


文本容器不支持文本选择。The text container does not support text selection.


private TextPatternRange CurrentSelection(AutomationElement target)
    // Specify the control type we're looking for, in this case 'Document'
    PropertyCondition cond = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document);

    // target --> The root AutomationElement.
    AutomationElement textProvider = target.FindFirst(TreeScope.Descendants, cond);

    TextPattern textpatternPattern = textProvider.GetCurrentPattern(TextPattern.Pattern) as TextPattern;

    if (textpatternPattern == null)
        Console.WriteLine("Root element does not contain a descendant that supports TextPattern.");
        return null;
    TextPatternRange[] currentSelection = textpatternPattern.GetSelection();
    return currentSelection[0];
Private Function CurrentSelection(ByVal target As AutomationElement) As TextPatternRange
    ' Specify the control type we're looking for, in this case 'Document'
    Dim cond As PropertyCondition = New PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Document)

    ' target --> The root AutomationElement.
    Dim textProvider As AutomationElement = target.FindFirst(TreeScope.Descendants, cond)

    Dim textpatternPattern As TextPattern = CType(textProvider.GetCurrentPattern(TextPattern.Pattern), TextPattern)

    If (textpatternPattern Is Nothing) Then
        Console.WriteLine("Root element does not contain a descendant that supports TextPattern.")
        Return Nothing
    End If
    Dim currentTextSelection As TextPatternRange() = textpatternPattern.GetSelection()
    Return currentTextSelection(0)
End Function


如果未选择任何文本,GetSelection 将在系统光标(文本插入点)的位置返回退化文本范围(空范围)。If no text is selected, GetSelection returns the degenerate text range (empty range) at the position of the system cursor (text insertion point).

如果系统光标(文本插入点)不存在,GetSelection 可能返回 nullIf the system cursor (text insertion point) is not present, GetSelection might return null.


使用 SupportedTextSelection 属性来测试控件是否支持文本插入点的文本选择或位置。Use the SupportedTextSelection property to test if text selection or positioning of the text insertion point is supported by the control.