所以这是我的问题。我希望我的上下文菜单打开一个ToolStrip。我已经成功了,但是上下文菜单只会在第二次右键单击之后打开。
我创建了一个简单的表单来显示问题。它包含一个带有一些menuStrip的toolStripMenuItems、一个空的contextMenuStrip和一个用于测试右键单击的按钮。所有这些都是用视觉工作室设计器创建的。下面是相关代码:
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。
我不明白,因为虽然上下文菜单项是动态添加的,但上下文菜单本身是在表单加载时初始化的。
那么,如何在第一次右键单击时打开上下文菜单呢?
发布于 2018-03-06 16:12:43
您的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");
}https://stackoverflow.com/questions/49134534
复制相似问题