How do I add a ContextMenuStrip to a ToolStripButton?

Simon picture Simon · Nov 12, 2008 · Viewed 10k times · Source

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?

Answer

Jason D picture Jason D · Nov 21, 2009

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));
        }
    }
}