ToolStripMenuItem:添加没有子菜单的箭头

ToolStripMenuItem: Add arrow without submenu

如何添加一个带有向右箭头的菜单项,就像有子菜单但不显示子菜单一样?

背景:对于托管 C# 应用程序,我想添加一个在非托管 DLL 中创建的子菜单(使用 TrackPopupMenu())。

在我的实验中,我只能在使用 "DropDownItems.Add" 附加项目时显示箭头。

我尝试使用

ToolStripMenuItem menu = new ToolStripMenuItem();
m_menu.Text = "Item that should have arrow w/o submenu";
m_menu.Click += this.OnMenuDoSomething;
m_menu.DropDownItems.Add("");

这仍然添加了一个子菜单。然后我尝试了这些组合:

m_menu.DropDownItems[0].Enabled = false;
m_menu.DropDownItems[0].Available = false;
m_menu.DropDownItems[0].Visible = false;

但是包含箭头的子菜单要么消失,要么什么都没有。

创建下拉菜单的句柄后,将其分配给 NativeWindow 以捕获 window 消息并隐藏绘制事件。事实上,您可以隐藏所有事件。

当您想显示下拉菜单时,只需松开 NativeWindow's 手柄即可。

例如

    private class NW : NativeWindow {
        public NW(IntPtr handle) {
            AssignHandle(handle);
        }

        const int WM_PAINT = 0xF;
        protected override void WndProc(ref Message m) {
            // can ignore all messages too
            if (m.Msg == WM_PAINT) {
                return;
            }
            base.WndProc(ref m);
        }
    }

    [STAThread]
    static void Main() {

        MenuStrip menu = new MenuStrip();

        NW nw = null; // declared outside to prevent garbage collection
        ToolStripMenuItem item1 = new ToolStripMenuItem("Item1");
        ToolStripMenuItem subItem1 = new ToolStripMenuItem("Sub Item1");
        subItem1.DropDown.DropShadowEnabled = false;
        subItem1.DropDown.HandleCreated += delegate {
            nw = new NW(subItem1.DropDown.Handle);
        };

        ToolStripMenuItem miMakeVisible = new ToolStripMenuItem("Make Visible");
        miMakeVisible.Click += delegate {
            if (nw != null) {
                nw.ReleaseHandle();
                nw = null;
            }
        };


        ToolStripMenuItem subItem2 = new ToolStripMenuItem("Sub Item2");
        item1.DropDownItems.Add(subItem1);
        item1.DropDownItems.Add(miMakeVisible);
        subItem1.DropDownItems.Add(subItem2);
        menu.Items.Add(item1);


        Form f = new Form();
        f.Controls.Add(menu);
        f.MainMenuStrip = menu;
        Application.Run(f);
    }