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 來判斷要放置自訂功能表的位置。 如需此範例,請參閱案例 2 的 ContextMenu 範例。 如需設計資訊,請參閱 操作功能表的指導方針

因為這個方法會傳回代表字元邊緣的矩形,所以傳回的矩形寬度一律為 0。 若要取得字元的寬度,您必須從尾端Rect的 X 值減去前置RectX值。

適用於