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

四角形を取得する文字の 0 から始まるインデックス。

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 値を減算する必要があります。

適用対象