将 ToolStripItem 添加到 ContextMenuStrip

Add ToolStripItem into ContextMenuStrip

所以这是我的问题。我想让我的上下文菜单打开一个 ToolStrip。我已经成功了,但是上下文菜单只会在第二次右键单击后打开。

我创建了一个简单的表格来显示问题。它包含一个带有一些 toolStripMenuItems 的 menuStrip、一个空的 contextMenuStrip 和一个用于测试右键单击的按钮。所有这些都是由 visual studio 设计器创建的。 下面是相关代码:

namespace Projet_test
{
  public partial class Form1 : Form
  {
    public Form1()
    {
      InitializeComponent(); //Contain this line: this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
    }

    //called by the Opening evenHandler of the context menu.
    private void contextOpening(object sender, CancelEventArgs e)
    {
      int j = 0;
      int total = menu1ToolStripMenuItem.DropDownItems.Count;
      for (int i = 0; i < total; i++)
      {
        contextMenuStrip1.Items.Insert(j, menu1ToolStripMenuItem.DropDownItems[0]);
        j++;
      }
    }

    //called by the Closed evenHandler of the context menu.
    private void contextClosed(object sender, ToolStripDropDownClosedEventArgs e)
    {
      int j = 0;
      int total = contextMenuStrip1.Items.Count;
      for (int i = 0; i < total; i++)
      {
        menu1ToolStripMenuItem.DropDownItems.Insert(j, contextMenuStrip1.Items[0]);
        j++;
      }
    }
  }
}

如您所见,右键单击该按钮将显示带有正确 ToolStripMenuItems 的上下文菜单,但仅在第二次单击之后..(并在第一次单击时清空 menuStrip,因为 toolStripMenuItem 不能位于两个位置同一时间)。

然后关闭上下文菜单将正确地重新创建 menuStrip。

我不明白,因为虽然上下文菜单项是动态添加的,但上下文菜单本身是在表单加载时初始化的。

那么如何才能在第一次右键单击时打开上下文菜单?

您的 ContextMenuStrip 是空的,这就是它没有显示任何内容的原因。尝试添加 "dummy" 项以触发菜单显示自身:

public Form1()
{
  InitializeComponent();
  contextMenuStrip1.Items.Add("dummy");
}

然后在添加新项目之前删除它:

private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {
  contextMenuStrip1.Items[0].Dispose();
  int j = 0;
  int total = menu1ToolStripMenuItem.DropDownItems.Count;
  for (int i = 0; i < total; i++) {
    contextMenuStrip1.Items.Insert(j, enu1ToolStripMenuItem.DropDownItems[0]);
    j++;
  }      
}

并在关闭时再次将其添加回来,这样菜单就不会再次为空:

private void contextMenuStrip1_Closed(object sender, ToolStripDropDownClosedEventArgs e) {
  int j = 0;
  int total = contextMenuStrip1.Items.Count;
  for (int i = 0; i < total; i++) {
    menu1ToolStripMenuItem.DropDownItems.Insert(j, contextMenuStrip1.Items[0]);
    j++;
  }
  contextMenuStrip1.Items.Add("dummy");
}