How can I assign a context menu to a toolstrip menu item in winform?

1.3k views Asked by At

I have a ToolStrip with a ToolStripDropDownButton to which I am adding ToolStripMenuItems in run time in my code. I need to have a default ContextMenuStrip and assign it to each menu item so when the user right clicks a menu item he will get that context menu strip. Is it possible ?

I appreciate your help.

2

There are 2 answers

0
Liran Friedman On BEST ANSWER

I found a good solution at: enter link description here

To save you the reading I also add the solutuin here:

void MenuItemContext(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left) return;

        ToolStripMenuItem mID = (ToolStripMenuItem)sender;

        ContextMenu tsmiContext = new ContextMenu();

        MenuItem Item1 = new MenuItem();
        MenuItem Item2 = new MenuItem();

        Item1.Text = "Item1";
        Item2.Text = "Item2";

        tsmiContext.MenuItems.Add(Item1);
        tsmiContext.MenuItems.Add(Item2);

        Item1.Click += new EventHandler(Item1_Click);
        Item2.Click += new EventHandler(Item2_Click);

        hndPass = mID.Text;

        tsmiContext.Show(menuStrip1, menuStrip1.PointToClient(new Point(Cursor.Position.X, Cursor.Position.Y)));
    }

    private String hndPass;

    void Item1_Click(object sender, EventArgs e)
    {
       MenuItem mID = (MenuItem)sender;
        MessageBox.Show("You clicked " + mID.Text + " in the context menu of " + hndPass);
    }
    void Item2_Click(object sender, EventArgs e)
    {
        MenuItem mID = (MenuItem)sender;
        MessageBox.Show("You clicked " + mID.Text + " in the context menu of " + hndPass); ;
    }

Have fun (-:

0
devavx On

Seems like I worked out something useful,this is obviously not perfect but should give you a decent starting point.I assume you've a ContextMenuStrip named contextmenustrip1,some drop down items of which one is aaaToolStripMenuItem.Then create a private boolean field,

private static bool clickReleased=false;

In the MouseDown event of aaaTool... write the following code;

if (e.Button == MouseButtons.Right)
   clickReleased = true;

then in MouseUp event,write this;

if (e.Button == MouseButtons.Right)
   {
   if (clickReleased)
      {
        contextMenuStrip1.Show(Cursor.Position);
        clickReleased = false;
      }
   }

Hope this helps.