转: (论坛答疑点滴)winform下怎么得到按钮的click事件的处理方法

转: http://www.cnblogs.com/lovecherry/archive/2005/06/13/173668.html

 

我们在做应用程序的时候有时候想知道页面上的按钮对于某一事件委托链上有多少方法,下面是一个例子。

1、先添加3个按钮,分别添加0个,1个,2个click事件的方法,按钮名字分别为button1,button2,button3。

this .button2.Click  +=   new  System.EventHandler( this .button2_Click);
this .button3.Click  +=   new  System.EventHandler( this .button3_Click1);
this .button3.Click  +=   new  System.EventHandler( this .button3_Click2);

2、方法里面可以随便写点代码:

     private   void  button2_Click( object  sender, System.EventArgs e)
        {
            MessageBox.Show(
" button2_Click " );
        }

        
private   void  button3_Click1( object  sender, System.EventArgs e)
        {        
            MessageBox.Show(
" button3_Click1 " );
        }

        
private   void  button3_Click2( object  sender, System.EventArgs e)
        {
            MessageBox.Show(
" button3_Click2 " );        
        }

3、再放一个textbox(textbox1)用来填写按钮的名字,一个listbox(listbox1)显示按钮的click事件处理方法,最后放置一个按钮,点击这个按钮显示textbox1填写的那个按钮的click事件的处理方法于listbox1上,代码如下:

if ( this .textBox1.Text == "" )
                MessageBox.Show(
" 填写一个按钮的id " );
            
else
            {
                Button btn
= null ;
                
foreach (Control c  in   this .Controls)
                    
if (c.Name == this .textBox1.Text)
                        btn
= (Button)c;
                
this .listBox1.Items.Clear();
                PropertyInfo pi
= ( typeof (Button)).GetProperty( " Events " ,BindingFlags.Instance | BindingFlags.NonPublic);
                EventHandlerList ehl
= (EventHandlerList)pi.GetValue(btn, null );
                FieldInfo fi
= ( typeof (Control)).GetField( " EventClick " ,BindingFlags.Static | BindingFlags.NonPublic);
                Delegate d
= ehl[fi.GetValue( null )];
                
if (d != null )                
                {
                    
foreach (Delegate de  in  d.GetInvocationList())
                        
this .listBox1.Items.Add(de.Method.Name);
                }
                
else
                {
                    
this .listBox1.Items.Add( " 没有任何处理方法 " );
                }
            }

别忘记
using  System.Reflection;

为何如此复杂?是因为这些控件的事件都封装到了EventHandlerList内,而它不是公共成员,因此还需要通过反射来剥离出来。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值