C#中一种窗体消息分发机制(实在太像Delphi了)

简化转载自http://www.cnblogs.com/lzcarl/archive/2005/08/09/210753.html

因为是转载别人的文章,所以先评价一下文中的方法:
文中所用的方法主要是依照按钮文字来决定调用逻辑。
优点:代码量/控件量不太多的情况下易于移植
缺点:对于控件上文字相同的情况无法处理,按钮文字可能在运行时需要更改,而更改后对应的逻辑可能与原来相同却要写重复的代码。。。。还有很多问题,用了就知道。。。
比较好的解决方法:个人认为比较好的解决方法(根据几年Delphi使用的经验)还是把逻辑尽可能地抽象,归类,土办法了。。。。。不过还是最扎实的方法。。。

以下为原文(省略部分代码和文字)

平常我们编写一个窗体事件的处理程序时通常是使用该事件的默认函数,比如button1_click(...),之类的。但这样做的话会出现界面元素与业务逻辑代码过度耦合的情况,比如我们在设计菜单的时候,想将一个菜单项的功能换到另一个菜单项里面,就比较麻烦了,需要进行大量的代码剪切复制,然后又要测试。在我看的例子里面,作者用同一个函数fnAllButtonsClicks作为每个窗体函数的响应事件函数。
    例如:
    this.btInsertnew.Click += new System.EventHandler(this.fnAllButtonsClicks);
    this.btUpdate.Click += new System.EventHandler(this.fnAllButtonsClicks);
    this.btDelete.Click += new System.EventHandler(this.fnAllButtonsClicks);
    ……

    在fnAllButtonsClicks里面,用switch if根据不同的事件调用不同的函数:

 1      // 这个程序的事件基本只涉及到按钮点击事件
 2            private   void  fnAllButtonsClicks( object  sender, System.EventArgs e)
 3        {
 4          Button bt=(Button)sender; //get which button clicked
 5          switch (bt.Text) //button-text
 6          {
 7          
 8              case "Insert":
                                              fnInsertNew();
 9                                       break;
11             case "Save/Update":
                                              fnSaveUpdate();                        
15                                     break;    
47             case "Exit":
                                              Application.Exit();                 
48                                     break;                            
49                                
50          }//switch
51      }


     然后编写每个处理函数的代码:
     fnSaveUpdate(){……}
     fnDelete(){……}
     ……

     由此可见,对界面上的改动就限制到fnAllButtonsClicks里面了。

     另外它的启用/禁用全部按钮的方法也不错(我以前的方法真的很笨的):

 1        // - This is the way to enable or disable ALL the buttons on the Form
 2        // - if flag true all buttons enabled, if false buttons disabled
 3        public   void  fnEnableDisableAllButtons( bool  flag) 
 4        {
 5         string str;
 6         foreach(Control ctrl in this.Controls) 
 7         {
 8            str = Convert.ToString(ctrl.GetType());
 9            if(str == "System.Windows.Forms.Button"
10            {
11              ctrl.Enabled = flag;
12            }
//if
13         }
//foreach
14      }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值