Subscribe

RSS Feed (xml)

Using Part of a Main Menu for a Context Menu

In many applications, a control's context-sensitive menu duplicates a portion of the main menu. However, .NET does not allow you to create a MenuItem instance that's contained in more than one menu at a time.

The solution is to make a duplicate copy of a portion of the menu using the CloneMenu method. The CloneMenu method not only copies the appropriate MenuItem items (and any contained submenus), it also registers each MenuItem object with the same event handlers. Thus, when a user clicks a cloned menu item in a context menu, the same event handler will be triggered as if the user clicked the duplicate menu item in the main menu.

For example, consider the test application shown in the following Figure. In this example, the context menu for the text box shows the same entries that are found in the File menu. Technically, these are duplicate copies of the appropriate MenuItem objects. However, if the user clicks on one of these entries, the same event handler is executed.

combo-box.JPG

Here's the form code you need to create this example. It duplicates the entries in the main menu when the form first loads. (Unfortunately, it's not possible to perform the same operation at design time.)

using System;
using System.Windows.Forms;
using System.Drawing;

public class ContextMenuCopy : System.Windows.Forms.Form {

    // (Designer code omitted.)

    private void ContextMenuCopy_Load(object sender, System.EventArgs e) {
    
        ContextMenu mnuContext = new ContextMenu();

        // Copy the menu items from the File menu into a context menu.
        foreach (MenuItem mnuItem in mnuFile.MenuItems) {

            mnuContext.MenuItems.Add(mnuItem.CloneMenu());
        }

        // Attach the context menu to the text box.
        TextBox1.ContextMenu = mnuContext;
    }

    private void TextBox1_MouseDown(object sender,
      System.Windows.Forms.MouseEventArgs e) {
   
        if (e.Button == MouseButtons.Right){

            TextBox1.ContextMenu.Show(TextBox1, new Point(e.X, e.Y));
        }
    }

    private void mnuOpen_Click(object sender, System.EventArgs e) {
    
        MessageBox.Show("This is the event handler for Open.");
    }

    private void mnuSave_Click(object sender, System.EventArgs e) {
    
        MessageBox.Show("This is the event handler for Save.");
    }

    private void mnuClick_Click(object sender, System.EventArgs e) {
    
        MessageBox.Show("This is the event handler for Exit.");
    }
}

Technorati :

No comments:

Post a Comment

Archives

LocalsAdda.com-Variety In Web World

Fun Mail - Fun in the Mail