新随笔  :: 联系 :: 订阅 订阅  :: 管理

.net button onclick..详细

Posted on 2009-12-07 13:09  sakiwer  阅读(120)  评论(0)    收藏  举报

两个简单文件...
Form1.cs
private void button1_Click(object sender, EventArgs e){}

Form1.Designer.cs
this.button1.Click += new System.EventHandler(this.button1_Click);

当我们点击按钮..就会调用 button1_Click函数..好简单..

但是.net底层为我们做了些什么事呢...
首先...main函数调用application.run()开始消息循环,进入消息循环就会把消息分发到窗口过程...
大家都知道鼠标点击会触发mouseup事件..form1继承了control类的wndproc方法..
wndproc内部{
//..
case 0x202: this.WmMouseUp(ref m, MouseButtons.Left, 1); return;
case 0x205: this.WmMouseUp(ref m, MouseButtons.Right, 1); return;
case 520: this.WmMouseUp(ref m, MouseButtons.Middle, 1); return;
//...
}///详细见前面2篇关于.net消息循环的文章看
..这里调用了wmmouseup函数...
我们来看看这个wmmouseup函数...
//..
if (!this.GetState(0x4000000))
{
this.OnClick(new MouseEventArgs(button, clicks, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0));
this.OnMouseClick(new MouseEventArgs(button, clicks, NativeMethods.Util.SignedLOWORD(m.LParam), NativeMethods.Util.SignedHIWORD(m.LParam), 0));
}
//...
这里调用了..onclick函数...
好吧 我们来看onclick函数....
protected virtual void OnClick(EventArgs e)
{
EventHandler handler = (EventHandler) base.Events[EventClick];
if
(handler != null) { handler(this, e); }
}
..这里有啥...(EventHandler) base.Events[EventClick];其实这个就是一个事件列表...
events的定义....
protected EventHandlerList Events{
get {
if (this.events == null) { this.events = new EventHandlerList(this); }
return
this.events;
}}

public sealed class EventHandlerList : IDisposable {

public void AddHandler(object key, Delegate value);

}

看到..public void AddHandler(object key, Delegate value);原来是把一个键值对加到事件列表...

在control类中看到这个.....

public event EventHandler Click
{
add
{
base.Events.AddHandler(EventClick, value);
}
remove
{
base.Events.RemoveHandler(EventClick, value);
}
}
什么意思..就是..
如果..我们这么this.button1.Click += new System.EventHandler(this.button1_Click);写..就把一个eventclick和new System.EventHandler(this.button1_Click)委托.加到事件列表中...
那么
eventclick又是啥呢..看定义...private static readonly object EventClick;...就是一个对象...

好嘛
..现在我们知道整个流程了.....
初始化组件时.....
this.button1.Click += ....把一个委托对象和eventclick添加到事件列表...
1:main函数启动,2,applction.run()进入消息循环,分发消息到窗口过程函数.3.收到mouseup消息,激发this.onclick()函数,4.从事件列表中寻找eventclick对象与之对应的委托对象..5,把它强转化为标准事件..然后通过handler(this,e)..激发..我们的Click事件...而click事件又绑定了我们的his.button1_Click方法..
就是这样
.................
类别:.net 查看评论