事件
来源:互联网 发布:手机显微镜软件 编辑:程序博客网 时间:2024/04/28 11:12
设计一个可统计单击次数的按钮,它提供一个自定义的MyClick事件
一、使用自定义事件的委托
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;namespace 事件练习{ /// <summary> /// 自定义按钮可以实现记录点击的次数 /// </summary> public class MyCustomButton:Button { /// <summary> /// 自定义事件的委托 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public delegate void MyClickDelegate(object sender, MyClickEventArgs e); /// <summary> /// 自定义事件 /// </summary> public event MyClickDelegate MyClick; int clickCount = 0; protected override void OnClick(EventArgs e) { clickCount++; if (MyClick != null) { //激发MyClick事件 MyClick(this, new MyClickEventArgs(clickCount)); } } } /// <summary> /// 定义MyClick事件参数 /// </summary> public class MyClickEventArgs : EventArgs { /// <summary> /// 点击次数 /// </summary> public int clickCount = 0; public MyClickEventArgs(int clickCountValue) { this.clickCount = clickCountValue; } }}二、使用泛型事件
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;namespace 事件练习{ /* 一、泛型委托的定义如下: [SerializableAttribute] public delegate void EventHandler<TEventArgs>( Object sender, TEventArgse ) where TEventArgs: EventArgs */ /*二、使用EventHandler<>的好处是: 1.只需定义好事件参数类(从EventArgs类派生) 2.不再需要定义独立的事件委托. */ /// <summary> /// 自定义按钮可以记录点击次数(使用了泛型委托) /// </summary> public class MyCustomButtonUseGenericscDelegate:Button { /// <summary> /// 使用泛型事件可以简化自定义事件 /// </summary> public event EventHandler<MyClickEventArgs> MyClick; int clickCount = 0; protected override void OnClick(EventArgs e) { clickCount++; if (MyClick != null) { MyClick(this, new MyClickEventArgs(clickCount)); } } }}三、前台注册事件
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;namespace 事件练习{ public partial class Form1 : Form { public Form1() { InitializeComponent(); //挂载事件 myCustomButton1.MyClick += new MyCustomButton.MyClickDelegate(myCustomButton1_MyClick); myCustomButtonUseGenericscDelegate1.MyClick += new EventHandler<MyClickEventArgs>(myCustomButtonUseGenericscDelegate1_MyClick); } void myCustomButtonUseGenericscDelegate1_MyClick(object sender, MyClickEventArgs e) { MessageBox.Show(string.Format("点击了{0}次按钮.", e.clickCount)); } void myCustomButton1_MyClick(object sender, MyClickEventArgs e) { MessageBox.Show(string.Format("点击了{0}次按钮.", e.clickCount)); } }}源代码下载:点击打开链接
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- 事件
- opencv实现图像旋转
- hdu 4128 Running relay ——2011ACM福州赛区H题
- NET START 服务名无效,拒绝访问
- 疯狂java 读书笔记
- 超级简单实现内容的左右移动js+jquery+html
- 事件
- effective C++ 继承与面向对象设计 笔记
- redhat enterprise linux 5 samba相关问题
- Oracle 数据字典 说明
- 1.有序顺序表的插入
- sa
- Linux C++面向对象多线程机制实现框架
- HDUOJ 2060 Snooker
- jquery_2