在 winforms 中单击时不要关闭 ToolStripMenu

Do not close ToolStripMenu on clicking in winforms

我在一个 c# winform 项目上工作,在用户单击它的项目后,主工具条菜单不必隐藏,我该怎么做?

设置父菜单项的自动关闭 属性 以防止菜单条关闭。

演示:

ToolStripMenuItem file = new ToolStripMenuItem("File");
file.DropDown.AutoClose = false;
file.DropDownItems.Add("New");
file.DropDownItems.Add("Open");
file.DropDownItems.Add("Exit");

MenuStrip ms = new MenuStrip();
ms.Items.Add(file);

this.Controls.Add(ms);

现在您有责任自行关闭菜单:

file.DropDown.Close();

我在 MSDN forum 上找到了更好的答案。下拉菜单在点击时不关闭,但在其他情况下关闭:

DropDown.Closing += new ToolStripDropDownClosingEventHandler(DropDown_Closing);
...
private void DropDown_Closing(object sender,  ToolStripDropDownClosingEventArgs e)
{
    if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked)
    {
        e.Cancel = true;
    }
}