WinForm-MenuStrip
1 ToolStrip menuStrip1; 2 public Form1() 3 { 4 InitializeComponent(); 5 menuStrip1 = new ToolStrip(); 6 this.Controls.Add(menuStrip1); 7 } 8 9 private void Form1_Load(object sender, EventArgs e) 10 { 11 //添加菜单一 12 ToolStripMenuItem subItem; 13 subItem = AddContextMenu("入库", menuStrip1.Items, null); 14 //添加子菜单 15 ToolStripMenuItem grandsonItem; 16 grandsonItem = AddContextMenu("添加入库", subItem.DropDownItems, new EventHandler(MenuClicked)); 17 AddContextMenu("大米", grandsonItem.DropDownItems, new EventHandler(MenuClicked)); 18 AddContextMenu("入库管理", subItem.DropDownItems, new EventHandler(MenuClicked)); 19 20 21 //添加菜单二 22 subItem = AddContextMenu("出库", menuStrip1.Items, null); 23 //添加子菜单 24 AddContextMenu("添加出库", subItem.DropDownItems, new EventHandler(MenuClicked)); 25 AddContextMenu("出库管理", subItem.DropDownItems, new EventHandler(MenuClicked)); 26 } 27 /// <summary> 28 /// 添加子菜单 29 /// </summary> 30 /// <param name="text">要显示的文字,如果为 - 则显示为分割线</param> 31 /// <param name="cms">要添加到的子菜单集合</param> 32 /// <param name="callback">点击时触发的事件</param> 33 /// <returns>生成的子菜单,如果为分隔条则返回null</returns> 34 35 ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback) 36 { 37 if (text == "-") 38 { 39 ToolStripSeparator tsp = new ToolStripSeparator(); 40 cms.Add(tsp); 41 return null; 42 } 43 else if (!string.IsNullOrEmpty(text)) 44 { 45 ToolStripMenuItem tsmi = new ToolStripMenuItem(text); 46 tsmi.Tag = text + "TAG"; 47 if (callback != null) tsmi.Click += callback; 48 cms.Add(tsmi); 49 50 return tsmi; 51 } 52 53 return null; 54 } 55 56 void MenuClicked(object sender, EventArgs e) 57 { 58 //以下主要是动态生成事件并打开窗体 59 60 //((sender as ToolStripMenuItem).Tag)强制转换 61 62 ObjectHandle t = Activator.CreateInstance("WinForms", "WinForms.Form2"); 63 Form f = (Form)t.Unwrap(); 64 f.ShowDialog(); 65 66 }