Fine-tuning control of your ToolStripItem overflow

Customer question:

Can I get a ToolStrip to overflow items in reverse order? That is, overflow the leftmost items before overflowing those to the right.  My scenario is to use a ToolStrip much like the address bar in the Vista Explorer:

Virtual Folder 1 > Virtual Folder 2 > ...

Once the ToolStrip is too small to hold the items, "Virtual Folder 1" should be the first to overflow.

Absolutely. Let me describe the simple case first. If you had items that were aligned both to the left and to the right edges of your toolstrip, the way the toolstrip picks to remove your items from the toolstrip is to walk from the end of the items collection removing items that do not fit. So if you want your aligned=left items to disappear before say a help button that's aligned to the right, you'd put the help button first in the items collection, then all your aligned left items.

Your case seems more special. Instead of gluing items to the left and right, all of your items are glued to the left, so the simple solution wont work here. That's when we go to plan B, which can be used to more generally control overflow in the toolstrip. You change the ToolStripItem.Overflow from being "AsNeeded" to "Never".

Then sync the LayoutCompleted event on the ToolStrip. When this occurs, you can inspect the ToolStripItem.Placement property to see whether or not the item was placed on Main or Overflow or None. You can then adjust the ToolStripItem.Overflow to manually place items "Always" in the overflow. Plan B is only going to work for you if you're not sheepish about doing a little math on your own.

When you're doing this, you'll want to know some interesting details:

The items space themselves out using their margin properties - so when counting in your item widths, you need to count in the Margin as well. This handy method calculates it for you:

                private static int GetItemWidth(ToolStripItem item) {
return item.Width + item.Margin.Horizontal;
}

When you're calculating how much room is left in the ToolStrip for items to display, you want to figure out the width of the toolstrip, minus space for the grip and overflow button. This is achieved by checking the DisplayRectangle of the ToolStrip and subtracting out the size of the overflow button if it's currently visible.

                 private static int GetToolStripInteriorWidth(ToolStrip toolStrip) {
int overflowButtonWidth = 0;
           if (toolStrip.OverflowButton.Visible) {
               overflowButtonWidth = GetItemWidth(toolStrip.OverflowButton);
}
           return toolStrip.DisplayRectangle.Width - overflowButtonWidth;
}

Here's a sample I quickly put together to solve this particular question. For more information, consult the ToolStrip FAQ.