This documentation is archived and is not being maintained.

Change Selection in a RichTextBox Programmatically

This example shows how to programmatically change the current selection in a RichTextBox. This selection is the same as if the user had selected the content by using the user interface.

The following Extensible Application Markup Language (XAML) code describes a named RichTextBox control with simple content.

<Page xmlns=""
  x:Class="SDKSample.ChangeSelectionProgrammaticaly" >

    <RichTextBox GotMouseCapture="ChangeSelection" Name="richTB">
        <Paragraph Name="myParagraph">
            When the user clicks in the RichTextBox, the selected
            text changes programmatically.


The following code programmatically selects some arbitrary text when the user clicks inside the RichTextBox.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace SDKSample
    public partial class ChangeSelectionProgrammaticaly : Page

        // Change the current selection. 
        void ChangeSelection(Object sender, RoutedEventArgs args)
            // Create two arbitrary TextPointers to specify the range of content to select.
            TextPointer myTextPointer1 = myParagraph.ContentStart.GetPositionAtOffset(20);
            TextPointer myTextPointer2 = myParagraph.ContentEnd.GetPositionAtOffset(-10);

            // Programmatically change the selection in the RichTextBox.
            richTB.Selection.Select(myTextPointer1, myTextPointer2);