이 예제에서는 RichTextBox에 사용할 사용자 지정 상황에 맞는 메뉴의 위치를 지정하는 방법을 보여 줍니다.
RichTextBox에 사용자 지정 상황에 맞는 메뉴를 구현하면 상황에 맞는 메뉴의 위치도 지정해야 합니다. 기본적으로 사용자 지정 상황에 맞는 메뉴는 RichTextBox의 가운데에서 열립니다.
예제
기본 배치 동작을 재정의하기 위해 ContextMenuOpening 이벤트에 대한 수신기를 추가합니다. 다음 예제에서는 프로그래밍 방식으로 이 작업을 수행하는 방법을 보여 줍니다.
AddHandler richTextBox.ContextMenuOpening, AddressOf 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.
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
// 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;
}