TextPointer.GetOffsetToPosition(TextPointer) Method

Definition

Returns the count of symbols between the current TextPointer and a second specified TextPointer.

C#
public int GetOffsetToPosition(System.Windows.Documents.TextPointer position);

Parameters

position
TextPointer

A TextPointer that specifies a position to find the distance (in symbols) to.

Returns

The relative number of symbols between the current TextPointer and position. A negative value indicates that the current TextPointer follows the position specified by position, 0 indicates that the positions are equal, and a positive value indicates that the current TextPointer precedes the position specified by position.

Exceptions

position specifies a position outside of the text container associated with the current position.

Examples

The following example demonstrates a use for this method. The example uses the GetOffsetToPosition method to find the offsets for two TextPointer instances, and then uses this information to save and restore the selection in a RichTextBox. The example assumes that the contents of the RichTextBox have not changed between a selection save and a selection restore.

C#
struct SelectionOffsets { internal int Start; internal int End; }
 
SelectionOffsets GetSelectionOffsetsRTB(RichTextBox richTextBox)
{
    SelectionOffsets selectionOffsets;
 
    TextPointer contentStart = richTextBox.Document.ContentStart;

    // Find the offset for the starting and ending TextPointers.
    selectionOffsets.Start = contentStart.GetOffsetToPosition(richTextBox.Selection.Start);
    selectionOffsets.End = contentStart.GetOffsetToPosition(richTextBox.Selection.End);

    return selectionOffsets;
}

void RestoreSelectionOffsetsRTB(RichTextBox richTextBox, SelectionOffsets selectionOffsets)
{
    TextPointer contentStart = richTextBox.Document.ContentStart;
 
    // Use previously determined offsets to create corresponding TextPointers,
    // and use these to restore the selection.
    richTextBox.Selection.Select(
       contentStart.GetPositionAtOffset(selectionOffsets.Start),
       contentStart.GetPositionAtOffset(selectionOffsets.End)
    );
}

Remarks

Any of the following is considered to be a symbol:

Applies to

Product Versions
.NET Framework 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

See also