实例002 菜单动态合并
操作步骤:
(1)新建 Windows窗体应用程序 项目,命名为 Ex01_02,默认窗体为 Form1。
(2)添加 MenuStrip 主菜单控件和 ContextMenuStrip 右键菜单控件,并分别添加项目,主菜单应添加 打开子窗体 栏目。
(3)点击vs2008上方的 项目 菜单,选择 添加Windows窗体,切换到 Windows Forms 选项,选择 Windows窗体,然后点击 添加,就为主窗体 Form1 添加了子窗体 Form2。
(4)输入代码。
(5)这时会出现两个错误,打开Form2.Designer.cs,
private System.Windows.Forms.ContextMenuStrip contextMenuStrip2;
改为
public System.Windows.Forms.ContextMenuStrip contextMenuStrip2;
(6)最后打开 Form1 的属性窗口,将 IsMdiContainer 的属性设置为 True。
完整代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Ex01_02
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void 打开子窗体ToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.MdiParent = this;
f.Show(); //显示子窗体
f.Resize += new EventHandler(f_Resize);
}
void f_Resize(object sender, EventArgs e)
{
Form2 f = (Form2)sender;
ToolStripMenuItem item = new ToolStripMenuItem();
for(int i = 0; i < f.contextMenuStrip2.Items.Count;) //合并菜单
{
item.DropDownItems.Add(f.contextMenuStrip2.Items[i]);
}
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[]{
item});
}
}
}

没有评论:
发表评论