Category / Section
How to associate a WinForms PopupMenu with a control for context menu-like behavior?
1 min read
Context menu
The PopupMenusManager lets you easily associate a PopupMenu with a control:
Through Designer
Once you drop a PopupMenusManager onto your form, you will see an extended "ContextMenu" property on all your controls. Set the property to the PopupMenu you just created. This will show the popup menu whenever you right-click on the control during run-time. If you want to show a popup menu during some other event, read below for instructions to manually display the popup.
Through Code
You can use the PopupMenusManager to associate a PopupMenu with a control as follows:
C#
this.popupMenusManager1.SetContextMenu(this.treeViewAdv1, this.popupMenu1);
VB
Me.popupMenusManager1.SetContextMenu(Me.treeViewAdv1, Me.popupMenu1)
Instead, you could show the popup menu manually, as follows:
C#
private void MouseClickedHandler(object sender, System.Windows.Forms.MouseEventArgs e) { if(e.Button == MouseButtons.Right) this.popupMenu1.Show((Control)sender, new Point(e.X, e.Y)); }
VB
Private Sub TreeViewAdv1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles TreeViewAdv1.MouseClick If e.Button = Windows.Forms.MouseButtons.Right Then Me.PopupMenu1.Show(CType(sender, Control), New Point(e.X, e.Y)) End If End Sub