Share via


TextBox.GetRectFromCharacterIndex(Int32, Boolean) 方法

定义

返回特定字符索引处字符的前导或尾边缘的矩形区域。

public:
 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

参数

charIndex
Int32

int

要为其检索矩形的字符的从零开始的索引。

trailingEdge
Boolean

bool

若要获取尾边,则为 true;如果为 false,则获取字符的前边缘。

返回

指定索引处字符边缘的矩形。

示例

此示例演示如何使用 GetRectFromCharacterIndex 来确定所选文本的矩形。 有关完整示例,请参阅 ContextMenu 示例的方案 2。

// 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);
    }
    else
    {
        rectFirst = textbox.GetRectFromCharacterIndex(textbox.SelectionStart, false);
    }

    int lastIndex = textbox.SelectionStart + textbox.SelectionLength;
    if (lastIndex == textbox.Text.Length)
    {
        rectLast = textbox.GetRectFromCharacterIndex(lastIndex - 1, true);
    }
    else
    {
        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;
    }
    else
    {
        x = point.X + rectLast.Right;
        dx = rectFirst.Left - rectLast.Right;
    }

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

注解

若要替代上下文菜单,请处理 ContextMenuOpening 事件,并将默认菜单替换为自定义菜单。 使用 GetRectFromCharacterIndex 确定自定义菜单的位置。 有关此内容的示例,请参阅 ContextMenu 示例的方案 2。 有关设计信息,请参阅 上下文菜单指南

由于此方法返回表示字符边缘的矩形,因此返回的矩形的宽度始终为 0。 若要获取字符的宽度,必须从尾随 RectX 值中减去前导 RectX 值。

适用于