C# WinForm 用MenuStrip动态生成菜单并动态加载事件

2011-09-27 11:13 by ※森林小居※, 2472 阅读, 9 评论, 收藏, 编辑

最近在做WINFORM开发,一直都在为主界面的点击事件及动态加载菜单苦脑。现在已解决这个问题了,可以实现数据库或都XML等配置完成动态生成菜单及事件加载。代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
private void Form1_Load( object sender, EventArgs e)
         {
             //添加菜单一 
             ToolStripMenuItem subItem;
             subItem = AddContextMenu( "入库" , menuStrip1.Items, null );
             //添加子菜单 
             AddContextMenu( "添加入库" , subItem.DropDownItems, new EventHandler(MenuClicked));
             AddContextMenu( "入库管理" , subItem.DropDownItems, new EventHandler(MenuClicked));
  
             //添加菜单二 
             subItem = AddContextMenu( "出库" , menuStrip1.Items, null );
             //添加子菜单 
             AddContextMenu( "添加出库" , subItem.DropDownItems, new EventHandler(MenuClicked));
             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();
  
         }

 

分类: C#
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值