共用方式為


操作說明:在 RichTextBox 中放置自訂操作功能表

此範例示範如何放置 的 RichTextBox 自訂操作功能表。

當您實作 RichTextBox 的自訂操作功能表時,需負責處理操作功能表的位置。 自訂操作功能表預設會在 RichTextBox 的中央開啟。

新增 CoNtextMenuOpening 事件的接聽程式

若要覆寫預設放置行為,請新增事件的接聽程式 ContextMenuOpening 。 下列範例顯示如何以程式設計方式執行此操作。

richTextBox.ContextMenuOpening += new ContextMenuEventHandler(richTextBox_ContextMenuOpening);
AddHandler richTextBox.ContextMenuOpening, AddressOf richTextBox_ContextMenuOpening

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;
}
' 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.
Private Sub richTextBox_ContextMenuOpening(ByVal sender As Object, ByVal e As ContextMenuEventArgs)
    ' Sender must be RichTextBox.
    Dim rtb As RichTextBox = TryCast(sender, RichTextBox)
    If rtb Is Nothing Then
        Return
    End If

    Dim contextMenu As 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.
    Dim position As TextPointer = rtb.Selection.End

    If position Is Nothing Then
        Return
    End If

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

    ' Finally, mark the event has handled.
    contextMenu.IsOpen = True
    e.Handled = True
End Sub

另請參閱