Question

In Winforms, I want to display a ContextMenuStrip when the user right-clicks on a ToolStripMenuItem. For example (see the image below), in Firefox there is Bookmarks menu and when we right-click on one of the bookmarks, a context menu item will be displayed.

How could we do it in Windows Form application?

I know we could associate a ContextMenuStrip to a Control (e.g. a Form), but the problem is that ToolStripMenuItem is not a Control.

bookmarks-menu-in-firefox

Was it helpful?

Solution

Create a custom ContextMenuStrip and show it while handling the MouseUp event on a ToolStripItem, so basically something like that:

    toolStripLabel1.MouseUp += new System.Windows.Forms.MouseEventHandler(toolStripLabel1_MouseUp);

    private void toolStripLabel1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            contextMenuStrip1.Show(Cursor.Position);
        }
    }

You can then display different context menus based on the menu item user clicked.

UPDATE

Regarding your comment, if you don't like the menu items to disapear when you show context menu, you can iterate through all the tool strip menu items and set AutoClose property to false (and then back to true after showing the context menu):

    private void toolStripLabel1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            AutoCloseDropDowns(menuStrip1.Items, false);
            contextMenuStrip1.Show(Cursor.Position);
            AutoCloseDropDowns(menuStrip1.Items, true);
        }
    }

    private void AutoCloseDropDowns(ToolStripItemCollection items, bool autoClose)
    {
        if (items != null)
        {
            foreach (var item in items)
            {
                var ts = item as ToolStripDropDownItem;
                if (ts != null)
                {
                    ts.DropDown.AutoClose = autoClose;
                    AutoCloseDropDowns(ts.DropDownItems, autoClose);
                }
            }
        }
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top