在 Winforms 中,我想在用户右键单击 ToolStripMenuItem 时显示 ContextMenuStrip。例如(见下图),在 Firefox 中有书签菜单,当我们右键单击其中一个书签时,将显示一个上下文菜单项。
我们如何在 Windows 窗体应用程序中做到这一点?
我知道我们可以将 ContextMenuStrip 关联到控件(例如窗体),但问题是 ToolStripMenuItem 不是控件。
在 Winforms 中,我想在用户右键单击 ToolStripMenuItem 时显示 ContextMenuStrip。例如(见下图),在 Firefox 中有书签菜单,当我们右键单击其中一个书签时,将显示一个上下文菜单项。
我们如何在 Windows 窗体应用程序中做到这一点?
我知道我们可以将 ContextMenuStrip 关联到控件(例如窗体),但问题是 ToolStripMenuItem 不是控件。
创建一个自定义 ContextMenuStrip 并在处理 ToolStripItem 上的 MouseUp 事件时显示它,所以基本上是这样的:
toolStripLabel1.MouseUp += new System.Windows.Forms.MouseEventHandler(toolStripLabel1_MouseUp);
private void toolStripLabel1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
contextMenuStrip1.Show(Cursor.Position);
}
}
然后,您可以根据用户单击的菜单项显示不同的上下文菜单。
更新
关于您的评论,如果您不希望在显示上下文菜单时菜单项消失,您可以遍历所有工具条菜单项并将AutoClose
属性设置为false
(然后true
在显示上下文菜单后返回):
private void toolStripLabel1_MouseUp(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
AutoCloseDropDowns(menuStrip1.Items, false);
contextMenuStrip1.Show(Cursor.Position);
AutoCloseDropDowns(menuStrip1.Items, true);
}
}
private void AutoCloseDropDowns(ToolStripItemCollection items, bool autoClose)
{
if (items != null)
{
foreach (var item in items)
{
var ts = item as ToolStripDropDownItem;
if (ts != null)
{
ts.DropDown.AutoClose = autoClose;
AutoCloseDropDowns(ts.DropDownItems, autoClose);
}
}
}
}