65.9K
CodeProject is changing. Read more.
Home

How to separate MenuItems with a horizontal line programatically

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.76/5 (10 votes)

Sep 20, 2011

CPOL
viewsIcon

44355

A MenuItem with special text is rendered as a separator

When my application needed a menu, I chose to code it instead of using the Visual Studio Designer (reasons are out of the scope of this tip).

Then, a new demand arose: a menu item separator should be placed between two menu items to strengthen the grouping of related menu items. But MainMenu doesn't accept a ToolStripSeparator to be added to it nor to its subitems.

But there is a workaround: Simply create a MenuItem with a single dash as descriptive text. It will get converted to a full-width menu item separator when rendered in the menu. A tiny code example follows:

this.Menu = new MainMenu();
this.Menu.Add(
    FirstMenuItem,
    SecondMenuItem,
    new MenuItem("-"),
    ThirdMenuItem
);

Hope it helps someone.