using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; namespace EventLearning { class Program { static void Main(string[] args) { //例一: // System.Timers.Timer timer = new System.Timers.Timer();//事件的拥有者 // timer.Interval = 1000; // Boy boy = new Boy();//事件的响应者 // Girl girl = new Girl(); // timer.Elapsed += girl.Action; // timer.Elapsed += boy.Action;//Elapsed是事件,+=是订阅,Action是事件处理器 // timer.Start(); // Console.ReadKey(); // //例二:事件的拥有者和响应者是不同对象 // Form form = new Form();//事件拥有者 // // Controller controller = new Controller(form);//controller事件响应者, // form.ShowDialog(); // //例三:事件的拥有者和响应者是相同对象 // MyForm myForm = new MyForm(); // myForm.Click += myForm.FormClicked; // myForm.ShowDialog(); // //例四:事件拥有者是事件响应者的字段成员,事件响应者用自己的方法订阅自己成员的事件 MyForm2 myForm2 = new MyForm2(); myForm2.ShowDialog(); } } class Controller { private Form _form; public Controller(Form form) { if (form!=null) { this._form = form; this._form.Click += this.FormClicked;//Click事件,+=订阅 } } private void FormClicked(object sender, EventArgs e)//事件处理器 { this._form.Text = DateTime.Now.ToString(); } } class MyForm : Form { internal void FormClicked(object sender, EventArgs e) { this.Text = DateTime.Now.ToString(); } } class MyForm2 : Form { private TextBox _textBox; private Button _button1; private Button _button2; private Button _button3; private Button _button4; public MyForm2() { this._textBox = new TextBox(); this._button1 = new Button(); this._button2 = new Button(); this._button3 = new Button(); this._button4 = new Button(); this.Controls.Add(this._button1); this.Controls.Add(this._button2); this.Controls.Add(this._button3); this.Controls.Add(this._button4); this.Controls.Add(this._textBox); this._button1.Click += this.ButtonClicked; this._button1.Text = "Say Hello"; this._button1.Top = 100; this._button2.Click += this.ButtonClicked; this._button2.Text = "Say World"; this._button2.Top = 130; this._button3.Click += new EventHandler(this.ButtonClicked);//传统挂接方式 this._button3.Text = "ML"; this._button3.Top = 160; this._button4.Click += (object sender, EventArgs e) => { this._textBox.Text = "hahahaha"; };//匿名函数委托形式挂接 this._button4.Text = "hahaha"; this._button4.Top = 190; } private void ButtonClicked(object sender, EventArgs e)//sender就是事件的发送者 { if (sender==this._button1) { this._textBox.Text = "Hello"; } if (sender == this._button2) { this._textBox.Text = "World"; } if (sender == this._button3) { this._textBox.Text = "ML"; } } } class Boy { //事件处理器 internal void Action(object sender, ElapsedEventArgs e) { Console.WriteLine("lala~"); } } class Girl { internal void Action(object sender, ElapsedEventArgs e) { Console.WriteLine("singing~"); } } }