menuStrip1動態添加菜單及快捷鍵


 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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM