| 网站首页 | 建站学院 | 资源下载 | 建站教程 | 图片素材 | 网贝社区 | 
您现在的位置: 网贝建站 >> 建站学院 >> ASP.NET >> winform应用 >> 正文 用户登录 新用户注册
专 题 栏 目
最 新 热 门
最 新 推 荐
相 关 文 章
如何得知调用当前方法的
通过事件,在两窗体间传
用Visual C#开发WinFor
[组图]winform下怎么得到按钮的click事件的处理方法         ★★★★
winform下怎么得到按钮的click事件的处理方法
作者:lovecher… 文章来源:http://www.cnblogs.com/lovecherry 点击数: 更新时间:2005-6-21 0:57:24

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

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内,而它不是公共成员,因此还需要通过反射来剥离出来。


文章录入:admin    责任编辑:admin 
  • 上一篇文章:

  • 下一篇文章:
  • 【字体: 】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口
      网友评论:(只显示最新10条。评论内容只代表网友观点,与本站立场无关!)