1 public partial class FormMkTest : Form
2 {
3 public FormMkTest()
4 {
5 InitializeComponent();
6 }
7
8 private void FormMkTest_Load(object sender, EventArgs e)
9 {
10 //添加菜单一文本中加入 &F 即ALT+F 打开某子菜单
11 ToolStripMenuItem subItem;
12 subItem = AddContextMenu("文件(&F)", menuStrip1.Items, null);
13 //添加子菜单
14 AddContextMenu("打开(&O)", subItem.DropDownItems, new EventHandler(MenuClicked));
15 AddContextMenu("下载(&D)", subItem.DropDownItems, new EventHandler(MenuClicked));
16
17 //添加菜单二
18 subItem = AddContextMenu("&Edit", menuStrip1.Items, null);
19 //添加子菜单
20 ToolStripMenuItem Grandson = AddContextMenu("&Update", subItem.DropDownItems, new EventHandler(MenuClicked));
21 //孙子
22 AddContextMenu("孙子级", Grandson.DropDownItems, new EventHandler(MenuClicked));
23 AddContextMenu("-", subItem.DropDownItems, null);//增加一个分割线
24 AddContextMenu("没有快捷键", subItem.DropDownItems, new EventHandler(MenuClicked));
25
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 void MenuClicked(object sender, EventArgs e)
56 {
57 //以下主要是动态生成事件并打开窗体
58
59 //((sender as ToolStripMenuItem).Tag)强制转换
60
61 //ObjectHandle t = Activator.CreateInstance("WinForms", "WinForms.Form2");
62 //Form f = (Form)t.Unwrap();
63 //f.ShowDialog();
64 string s = (sender as ToolStripMenuItem).Text;
65 MessageBox.Show(s);
66 }
67 }
string mStr = "武藤兰(&F)";
string mStred = Regex.Replace(mStr, "\(&.?\)", "");
Console.Write(mStred);