views:

1784

answers:

4

I have a toolstrip containing, among other things, a ToolStripComboBox and a ToolStripButton. I want to add a ContextMenuStrip to both of them, but I don't have direct access to the toolstrip or its other contents, so I can't set the context menu of the toolstrip.

Setting the ContextMenuStrip for the ToolStripComboBox is easy:

myToolStripComboBox.ComboBox.ContextMenuStrip = myContextMenu;

but there's no obvious equivalent for the ToolStripButton. How do I add a ContextMenuStrip to a ToolStripButton?

A: 

It's because a ToolStripComboBox contains "System.Windows.Forms.ComboBox" control, but "ToolStripButton" does not contains "System.Windows.Forms.Control". Its special toolstrip item, which's button is maintained by toolstip.

You should use ContextMenu on toolstip or you can add dropdown to toolstripbutton item.

TcKs
+2  A: 

You will need to set the context menu to the ToolStrip and then handle the Popup of the context menu or a related event and hit test which button the mouse is over to determine if you should show the ToolStrip's context menu and what it should contain.

Jeff Yates
A: 

Good question. You might be able to get access to the parent toolstrip (myToolStripButton.Parent or something similar) and attach the context-menu there.

AlexeyMK
+1  A: 

What Jeff Yates has suggested should work.

However, another alternative is to create your own derived classes (MyToolSTripButton, MyToolStripTextBox ...etc) give these items a ContextMenuStrip property that you can set at design time, and have your derived classes detect the right mouse down, or whatever other events will trigger the display of the context menu.

This offloads any of the knowledge needed to only those items interested.

Below is one such example using ToolStripTextBox as the item.

public class MyTextBox : ToolStripTextBox
{
    ContextMenuStrip _contextMenuStrip;

    public ContextMenuStrip ContextMenuStrip
    {
        get { return _contextMenuStrip; }
        set { _contextMenuStrip = value; }
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            if (_contextMenuStrip !=null)
                _contextMenuStrip.Show(Parent.PointToScreen(e.Location));
        }
    }
}
Jason D
Small thing: I think most people would find it more agreeable to use `contextMenu.Show(Cursor.Position);` instead of the `Parent.PointToScreen(e.Location)` business, which will usually only position the menu correctly for the first ToolStripItem
Toji