Subscribe

RSS Feed (xml)

How To Link a Context Menu to a Control

You can link a control to a context menu by settings the control's ContextMenu property. However, this is only a convenience-to display the context menu you must retrieve the menu and call its Show method, supplying both a parent control and a pair of coordinates. Usually, you implement this logic in an event handler for the MouseDown event.

The good news is that the logic for showing a context menu is completely generic, no matter what the control is. Every control supports the ContextMenu property (which is inherited from the base Control class), which means you can easily write a generic event handler that will display context menus for all controls.

For example, consider a form with a label, a picture box, and a text box. You can write a single event handler that responds to the MouseDown event for all these objects. Here's how the designer code would look if you connected all these events to an event handler named Control_MouseDown:

this.label1.MouseDown += new MouseEventHandler(this.Control_MouseDown);
this.pictureBox1.MouseDown += new MouseEventHandler(this.Control_MouseDown);
this.textBox1.MouseDown += new MouseEventHandler(this.Control_MouseDown);

The event-handling code is completely generic. It just casts the sender to a Control, checks for a linked context menu, and displays it.

private void Control_MouseDown(object sender,
  System.Windows.Forms.MouseEventArgs e) {

    if (e.Button == MouseButtons.Right) {
    
        // Get the source control.
        Control ctrl = (Control)sender;

        if (ctrl.ContextMenu != null) {
        
            // Show the linked menu over the control.
            ctrl.ContextMenu.Show(ctrl, new Point(e.X, e.Y));
        }
    }
}

Technorati :

1 comment:

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail