标签:get mes cli task this += style host you
Form2中的输入传到Form1中textBox中:
Form2作为事件发送者:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form2 : Form { //事件发送者 public delegate void OnClickHandler(string strMsg); public event OnClickHandler OnClickEvent; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if (OnClickEvent != null) { //textBox1.Text.ToString() 是作为事件参数发送到额 OnClickEvent(textBox1.Text.ToString()); } } } }
Form1是事件接受者:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //事件接受者 private void button1_Click(object sender, EventArgs e) { Form2 f2 = new Form2(); f2.OnClickEvent += new Form2.OnClickHandler(GetText); f2.Show(); } private void GetText(string strMsg) { textBox1.Text = strMsg; } } }
另外参考一下网上看到的一个委托和事件的小程序:
“现在我们来编写一个自定义事件的程序。主人养了一条忠实的看门狗,晚上主人睡觉的时候,狗负责看守房子。一旦有小偷进来,狗就发出一个Alarm事件,主人接到Alarm事件后就会采取相应的行动。假设小偷于2009年元旦午夜时分到达。”
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { //事件发送者 class Dog { //1.声明关于事件的委托 public delegate void AlarmEventHandler(object sender, EventArgs e); //2.声明事件 public event AlarmEventHandler Alarm; //3.编写引发事件的函数 public void OnAlarm() { if (this.Alarm != null) { Console.WriteLine("Dog Alarm: the thief is coming , worf!"); this.Alarm(this, new EventArgs()); } } } //事件接受者 class Host { //4.编写事件处理程序 void HostHandleAlarm(object sender, EventArgs e) { Console.WriteLine("Host: Catch you!"); } //5.注册事件处理程序 public Host(Dog dog) { dog.Alarm += new Dog.AlarmEventHandler(HostHandleAlarm); } } //6.现在来触发事件 class Program { static void Main(string[] args) { Dog dog = new Dog(); Host host = new Host(dog); DateTime now = new DateTime(2008, 12, 31, 23, 59, 50); DateTime midnight = new DateTime(2009, 1, 1, 0, 0,0); Console.WriteLine("Time flowing..."); while (now < midnight) { Console.WriteLine("Time:" + now); System.Threading.Thread.Sleep(1000); now = now.AddSeconds(1); } Console.WriteLine("MidNight:" + now); Console.WriteLine("The thief is coming..."); dog.OnAlarm(); Console.ReadKey(); } } }
标签:get mes cli task this += style host you
原文地址:https://www.cnblogs.com/samshen1991/p/8758785.html