menuStrip1動態添加菜單及快捷鍵
阿新 • • 發佈:2019-04-09
div handler name handle date tools ret cli ini
public partial class FormMkTest : Form { public FormMkTest() { InitializeComponent(); } private void FormMkTest_Load(object sender, EventArgs e) { //添加菜單一文本中加入 &F 即ALT+F 打開某子菜單 ToolStripMenuItem subItem; subItem = AddContextMenu("文件(&F)", menuStrip1.Items, null); //添加子菜單 AddContextMenu("打開(&O)", subItem.DropDownItems, new EventHandler(MenuClicked)); AddContextMenu("下載(&D)", subItem.DropDownItems, new EventHandler(MenuClicked)); //添加菜單二 subItem = AddContextMenu("&Edit", menuStrip1.Items, null); //添加子菜單 ToolStripMenuItem sub1 = AddContextMenu("&Update", subItem.DropDownItems, new EventHandler(MenuClicked)); //孫子 AddContextMenu("孫子", sub1.DropDownItems, new EventHandler(MenuClicked)); AddContextMenu("-", subItem.DropDownItems, null);//增加一個分割線 AddContextMenu("沒有快捷鍵", subItem.DropDownItems, new EventHandler(MenuClicked)); } /// <summary> /// 添加子菜單 /// </summary> /// <param name="text">要顯示的文字,如果為 - 則顯示為分割線</param> /// <param name="cms">要添加到的子菜單集合</param> /// <param name="callback">點擊時觸發的事件</param> /// <returns>生成的子菜單,如果為分隔條則返回null</returns> ToolStripMenuItem AddContextMenu(string text, ToolStripItemCollection cms, EventHandler callback) { if (text == "-") { ToolStripSeparator tsp = new ToolStripSeparator(); cms.Add(tsp); return null; } else if (!string.IsNullOrEmpty(text)) { ToolStripMenuItem tsmi = new ToolStripMenuItem(text); tsmi.Tag = text + "TAG"; if (callback != null) tsmi.Click += callback; cms.Add(tsmi); return tsmi; } return null; } void MenuClicked(object sender, EventArgs e) { //以下主要是動態生成事件並打開窗體 //((sender as ToolStripMenuItem).Tag)強制轉換 //ObjectHandle t = Activator.CreateInstance("WinForms", "WinForms.Form2"); //Form f = (Form)t.Unwrap(); //f.ShowDialog(); string s = (sender as ToolStripMenuItem).Text; MessageBox.Show(s); } }
menuStrip1動態添加菜單及快捷鍵