簡體   English   中英

將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。

我不明白,因為上下文菜單項是動態添加的,但是上下文菜單本身是在Form加載時初始化的。

那么如何在第一次單擊右鍵時打開上下文菜單?

您的ContextMenuStrip為空,這就是為什么它不顯示任何內容的原因。 嘗試添加“虛擬”項目以觸發菜單以顯示自身:

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");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM