C#怎么动态添加MenuStrip的菜单

C#怎么动态添加MenuStrip的菜单,第1张

你可以先在设计器里手动添加,然后在Designer.cs里找到相应代码剪切过来就行,如下

private System.Windows.Forms.MenuStrip menuStrip1

private System.Windows.Forms.ToolStripMenuItem aAAToolStripMenuItem

private System.Windows.Forms.ToolStripMenuItem bBBToolStripMenuItem

private void button1_Click(object sender, EventArgs e)

{

this.menuStrip1 = new System.Windows.Forms.MenuStrip()

this.aAAToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem()

this.bBBToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem()

//

// menuStrip1

//

this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {

this.aAAToolStripMenuItem})

this.menuStrip1.Location = new System.Drawing.Point(0, 0)

this.menuStrip1.Name = "menuStrip1"

this.menuStrip1.Size = new System.Drawing.Size(524, 24)

this.menuStrip1.TabIndex = 3

this.menuStrip1.Text = "menuStrip1"

//

// aAAToolStripMenuItem

//

this.aAAToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {

this.bBBToolStripMenuItem})

this.aAAToolStripMenuItem.Name = "aAAToolStripMenuItem"

this.aAAToolStripMenuItem.Size = new System.Drawing.Size(40, 20)

this.aAAToolStripMenuItem.Text = "AAA"

//

// bBBToolStripMenuItem

//

this.bBBToolStripMenuItem.Name = "bBBToolStripMenuItem"

this.bBBToolStripMenuItem.Size = new System.Drawing.Size(152, 22)

this.bBBToolStripMenuItem.Text = "BBB"

this.bBBToolStripMenuItem.Click += new System.EventHandler(this.bBBToolStripMenuItem_Click)

//

//Form1

//

this.Controls.Add(this.menuStrip1)

}

private void bBBToolStripMenuItem_Click(object sender, EventArgs e)

{

MessageBox.Show("BBB")

}

你既然已经会动态添加按钮了,那就完成一大半了。

你可以定义一个事件方法,将所有动态添加的按钮的click事件全部绑定至这个方法中。

然后,再根据sender参数,对传进来的菜单对象进行处理,就能实现你的这个功能。

你需要把ToolStripMenuItem强制转换为ToolStripDropDownItem类型才能添加子项,其实你自己看看Form1.Designer.cs里设计器自动生成的代码就会明白了,方法如下

private void button1_Click(object sender, EventArgs e)

{

((ToolStripDropDownItem)(((ToolStripDropDownItem)contextMenuStrip1.Items["aToolStripMenuItem"]).DropDownItems["eToolStripMenuItem"])).DropDownItems.Add(new ToolStripMenuItem("h"))

//或者

ToolStripDropDownItem ts = ((ToolStripDropDownItem)contextMenuStrip1.Items["aToolStripMenuItem"])

ts = ((ToolStripDropDownItem)ts.DropDownItems["eToolStripMenuItem"])

ts.DropDownItems.Add(new ToolStripMenuItem("h"))

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11599233.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-17
下一篇 2023-05-17

发表评论

登录后才能评论

评论列表(0条)

保存