Can I create a multiple-column context menu in .NE

2019-06-22 15:36发布

问题:

I want to create a context menu that has several columns. Basically it would go like this:

First item  | [common option] | All Options >
Second item | [common option] | All Options >
Third item  | [common option] | All Options >
Fourth item | [common option] | All Options >

So basically there are a bunch of items (generated at runtime), each item can be launched on its own; or with a commonly used option; or you can get a submenu with all possible options.

How can I do this? I'm trying to abuse both ContextMenuStrip and ContextMenu, yet they don't seem to have any such options. Still I seem to recall having seen multi-column menus somewhere...

I'd prefer a Windows Forms solution, because I don't have any WPF experience. Oh, and this context menu will open when clicking on an icon in the Notification Area (aka systray).

回答1:

I don't know about ContextMenuStrip, which is a menu built entirely in .NET code, but you can definitely do this with ContextMenu, which is a wrapper over the native system menus.

The key is setting the MFT_MENUBREAK or MFT_MENUBARBREAK flags for the individual menu item(s), which are exposed as properties in the MenuItem class wrapper: MenuItem.Break and MenuItem.BarBreak, respectively.

The former just places the menu item in a new column, while the latter places the item into a new column and separates the column with an etched vertical line.

From the MSDN example:

public void CreateMyMenus()
{
    // Create three top-level menu items.
    MenuItem menuItem1 = new MenuItem("&File");
    MenuItem menuItem2 = new MenuItem("&New");
    MenuItem menuItem3 = new MenuItem("&Open");

    // Set the BarBreak property to display horizontally.
    menuItem2.BarBreak = true;
    menuItem3.BarBreak = true;

    // Add menuItem2 and menuItem3 to the menuItem1's list of menu items.
    menuItem1.MenuItems.Add(menuItem2);
    menuItem1.MenuItems.Add(menuItem3);
}


回答2:

Menus in WinForms can only be built like trees: you can have a submenu under each item. So you can put the common option as the first item of the submenu.

It cannot look any different unless you design your own control (and then WPF is much more suitable for this task, but WPF takes a lot of time to learn).