TextBox.GetRectFromCharacterIndex(Int32, Boolean) Method


Returns a rectangular region for the leading or trailing edge of a character at a specific character index.

 virtual Rect GetRectFromCharacterIndex(int charIndex, bool trailingEdge) = GetRectFromCharacterIndex;
Rect GetRectFromCharacterIndex(int const& charIndex, bool const& trailingEdge);
public Rect GetRectFromCharacterIndex(int charIndex, bool trailingEdge);
function getRectFromCharacterIndex(charIndex, trailingEdge)
Public Function GetRectFromCharacterIndex (charIndex As Integer, trailingEdge As Boolean) As Rect




A zero-based index of the character for which to retrieve the rectangle.



true to get the trailing edge; false to get the leading edge of the character.



A rectangle for the edge of the character at the specified index.


This example shows how to use GetRectFromCharacterIndex to determine the rectangle for the selected text. For the complete example, see Scenario 2 of the ContextMenu sample.

// Returns a rect for selected text.
// If no text is selected, returns caret location.
// Text box should not be empty.
private Rect GetTextboxSelectionRect(TextBox textbox)
    Rect rectFirst, rectLast;
    if (textbox.SelectionStart == textbox.Text.Length)
        rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart - 1, true);
        rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart, false);

    int lastIndex = textbox.SelectionStart + textbox.SelectionLength;
    if (lastIndex == textbox.Text.Length)
        rectLast = textbox.GetRectFromCharacterIndex(lastIndex - 1, true);
        rectLast = textbox.GetRectFromCharacterIndex(lastIndex, false);

    GeneralTransform buttonTransform = textbox.TransformToVisual(null);
    Point point = buttonTransform.TransformPoint(new Point());

    // Make sure that we return a valid rect if selection is on multiple lines
    // and end of the selection is to the left of the start of the selection.
    double x, y, dx, dy;
    y = point.Y + rectFirst.Top;
    dy = rectLast.Bottom - rectFirst.Top;
    if (rectLast.Right > rectFirst.Left)
        x = point.X + rectFirst.Left;
        dx = rectLast.Right - rectFirst.Left;
        x = point.X + rectLast.Right;
        dx = rectFirst.Left - rectLast.Right;

    return new Rect(x, y, dx, dy);


To override the context menu, handle the ContextMenuOpening event and replace the default menu with a custom menu. Use GetRectFromCharacterIndex to determine where to position the custom menu. For an example of this, see Scenario 2 of the ContextMenu sample. For design info, see Guidelines for context menus.

Because this method returns a rectangle that represents a character edge, the width of the rectangle that's returned is always 0. To get the width of a character, you must subtract the X value of the leading Rect from the X value of the trailing Rect.

Applies to