R – ToolStrip Overflow

netwinforms

I need to replace the standard Overflow function in a ToolStrip to a "More…" button which would then pop up a menu with the overflowed items. Does anyone have any ideas about how to accomplish this?

Best Answer

I wrote something very similar to this awhile ago. The code I used is pasted below, and you are free to modify it to suit your needs.

The ToolStripCustomiseMenuItem is basically your "More" button that populates a DropDown Context Menu when clicked. Hope this helps you, at the very least this should be a good starting point…

  public class ToolStripCustomiseMenuItem : ToolStripDropDownButton {
        public ToolStripCustomiseMenuItem()
            : base("Add Remove Buttons") {
            this.Overflow = ToolStripItemOverflow.Always;
            DropDown = CreateCheckImageContextMenuStrip();
        }

    ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip();
    internal ContextMenuStrip CreateCheckImageContextMenuStrip() {
        ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip();
        checkImageContextMenuStrip.ShowCheckMargin = true;
        checkImageContextMenuStrip.ShowImageMargin = true;
        checkImageContextMenuStrip.Closing += new ToolStripDropDownClosingEventHandler(checkImageContextMenuStrip_Closing);
        checkImageContextMenuStrip.Opening += new CancelEventHandler(checkImageContextMenuStrip_Opening);
        DropDownOpening += new EventHandler(ToolStripAddRemoveMenuItem_DropDownOpening);
        return checkImageContextMenuStrip;
    }

    void checkImageContextMenuStrip_Opening(object sender, CancelEventArgs e) {

    }

    void ToolStripAddRemoveMenuItem_DropDownOpening(object sender, EventArgs e) {
        DropDownItems.Clear();
        if (this.Owner == null) return;
        foreach (ToolStripItem ti in Owner.Items) {
            if (ti is ToolStripSeparator) continue;
            if (ti == this) continue;
            MyToolStripCheckedMenuItem itm = new MyToolStripCheckedMenuItem(ti);
            itm.Checked = ti.Visible;
            DropDownItems.Add(itm);
        }
    }

    void checkImageContextMenuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e) {
        if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) {
            e.Cancel = true;
        }
    }
}

internal class MyToolStripCheckedMenuItem : ToolStripMenuItem {
    ToolStripItem tsi;
    public MyToolStripCheckedMenuItem(ToolStripItem tsi)
        : base(tsi.Text) {
        this.tsi = tsi;
        this.Image = tsi.Image;
        this.CheckOnClick = true;
        this.CheckState = CheckState.Checked;
        CheckedChanged += new EventHandler(MyToolStripCheckedMenuItem_CheckedChanged);
    }

    void MyToolStripCheckedMenuItem_CheckedChanged(object sender, EventArgs e) {
        tsi.Visible = this.Checked;
    }

}