次の方法で共有


方法 : カスタム コンテキスト メニューを RichTextBox に配置する

更新 : 2007 年 11 月

この例では、RichTextBox にカスタム コンテキスト メニューを配置する方法を示します。

RichTextBox へのカスタム コンテキスト メニューの実装では、コンテキスト メニューの配置を処理する必要があります。既定では、カスタム コンテキスト メニューは RichTextBox の中央で開かれます。

この例の具体的なサンプルについては、「RichTextBox でのカスタム コンテキスト メニューの配置のサンプル」を参照してください。

使用例

既定の配置動作を上書きするには、ContextMenuOpening イベントのリスナを追加します。プログラムでこれを実行する方法を次の例に示します。

richTextBox.ContextMenuOpening += new ContextMenuEventHandler(richTextBox_ContextMenuOpening);

対応する ContextMenuOpening イベントのリスナの実装例を次に示します。

// This method is intended to listen for the ContextMenuOpening event from a RichTextBox.
// It will position the custom context menu at the end of the current selection.
void richTextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    // Sender must be RichTextBox.
    RichTextBox rtb = sender as RichTextBox;
    if (rtb == null) return;

    ContextMenu contextMenu = rtb.ContextMenu;
    contextMenu.PlacementTarget = rtb;

    // This uses HorizontalOffset and VerticalOffset properties to position the menu,
    // relative to the upper left corner of the parent element (RichTextBox in this case).
    contextMenu.Placement = PlacementMode.RelativePoint;

    // Compute horizontal and vertical offsets to place the menu relative to selection end.
    TextPointer position = rtb.Selection.End;

    if (position == null) return;

    Rect positionRect = position.GetCharacterRect(LogicalDirection.Forward);
    contextMenu.HorizontalOffset = positionRect.X;
    contextMenu.VerticalOffset = positionRect.Y;

    // Finally, mark the event has handled.
    contextMenu.IsOpen = true;
    e.Handled = true;
}

参照

概念

RichTextBox の概要

TextBox の概要