ContextMenu.Popup Event

Definition

Occurs before the shortcut menu is displayed.

C#
public event EventHandler Popup;

Event Type

Examples

The following code example creates an event handler for the Popup event of the ContextMenu. The code in the event handler determines which of two controls a PictureBox named pictureBox1 and a TextBox named textBox1 is the control displaying the shortcut menu. Depending on which control caused the ContextMenu to display its shortcut menu, the control adds the appropriate MenuItem objects to the ContextMenu. This example requires that you have an instance of the ContextMenu class, named contextMenu1, defined within the form. This example also requires that you have a TextBox and PictureBox added to a form and that the ContextMenu property of these controls is set to contextMenu1.

C#
private void MyPopupEventHandler(System.Object sender, System.EventArgs e)
 {
    // Define the MenuItem objects to display for the TextBox.
    MenuItem menuItem1 = new MenuItem("&Copy");
    MenuItem menuItem2 = new MenuItem("&Find and Replace");
    // Define the MenuItem object to display for the PictureBox.
    MenuItem menuItem3 = new MenuItem("C&hange Picture");

    // Clear all previously added MenuItems.
    contextMenu1.MenuItems.Clear();
 
    if(contextMenu1.SourceControl == textBox1)
    {
       // Add MenuItems to display for the TextBox.
       contextMenu1.MenuItems.Add(menuItem1);
       contextMenu1.MenuItems.Add(menuItem2);
    }
    else if(contextMenu1.SourceControl == pictureBox1)
    {
       // Add the MenuItem to display for the PictureBox.
       contextMenu1.MenuItems.Add(menuItem3);
    }
 }

Remarks

You can use this event to initialize the MenuItem objects before they are displayed. For example, if you use a ContextMenu for three TextBox controls and you want to disable certain menu items in the ContextMenu depending on which TextBox is displaying the shortcut menu, you can create an event handler for this event. You could use the SourceControl property to determine which TextBox is about to display the ContextMenu and disable the appropriate MenuItem objects.

For more information about handling events, see Handling and Raising Events.

Applies to

Produkt Verzie
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 10