6.11 Link a Context Menu to a Control


Problem

You need to link a different context menu to each control on a form. However, you don't want to write a separate event handler to show the context menu for each control.

Solution

Write a generic event handler that retrieves the ContextMenu instance that's associated with a control and then displays the menu over the appropriate control.

Discussion

You can link a control to a context menu by settings the control's ContextMenu property. However, this is only a convenienceto 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));         }     } } 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net