最近在接触“委托事件”的使用,只是刚刚入门,还有有待于更深入地去研究和运用。
这是我做的一个简单的“运用委托事件,在窗体中传递信息”小程序,用于加深对“委托事件”的理解。
Form1中的代码为:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsWindows
{
public partial class Form1 : Form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public Form1()
{
InitializeComponent();
}
private void buttonX1_Click(object sender, EventArgs e)
{
Form2 form2 = new Form2(); //实例化窗体form2
form2.Form1 = this; //指定Form1为主窗体
form2.Show(); //打开窗体
}
public void Myupdate(string Mytext) //声明一个 Myupdate的方法
{
this.textBoxX1.Text = Mytext; //获取textBoxX1内的内容
}
public void Myupdate1(string Mytext1)//声明一个 Myupdate1的方法
{
this.textBoxX2.Text = Mytext1; //获取textBoxX1内的内容
}
{
Form2 form2 = new Form2(); //实例化窗体form2
form2.Form1 = this; //指定Form1为主窗体
form2.Show(); //打开窗体
}
public void Myupdate(string Mytext) //声明一个 Myupdate的方法
{
this.textBoxX1.Text = Mytext; //获取textBoxX1内的内容
}
public void Myupdate1(string Mytext1)//声明一个 Myupdate1的方法
{
this.textBoxX2.Text = Mytext1; //获取textBoxX1内的内容
}
private void buttonX2_Click(object sender, EventArgs e)
{
Form3 form3 = new Form3(); //实例化窗体form3
form3.Form1 = this; //指定form3为主窗体
form3.Show(); //打开form3窗体
}
}
}
{
Form3 form3 = new Form3(); //实例化窗体form3
form3.Form1 = this; //指定form3为主窗体
form3.Show(); //打开form3窗体
}
}
}
————————————————————————————————————————————
Form2中的代码为:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsWindows
{
public partial class Form2 : Form
{
public Form1 Form1; //声明Form1
public Form2()
{
InitializeComponent();
}
{
public partial class Form2 : Form
{
public Form1 Form1; //声明Form1
public Form2()
{
InitializeComponent();
}
public delegate void updata(string text); //声明一个枚举委托事件
private void textBoxX1_TextChanged(object sender, EventArgs e)
{
string Str_F2_Text = textBoxX1.Text; //声明一个字符串变量,用于存储textBoxX1的内容
updata Strupdata = new updata(Form1.Myupdate); //实例化 (其中Form1.Myupdate是指Form1中的方法)
IAsyncResult IAsync = this.BeginInvoke(Strupdata, new object[] { Str_F2_Text }); //执行委托事件
}
}
}
{
string Str_F2_Text = textBoxX1.Text; //声明一个字符串变量,用于存储textBoxX1的内容
updata Strupdata = new updata(Form1.Myupdate); //实例化 (其中Form1.Myupdate是指Form1中的方法)
IAsyncResult IAsync = this.BeginInvoke(Strupdata, new object[] { Str_F2_Text }); //执行委托事件
}
}
}
————————————————————————————————————————————
窗体Form3的代码跟Form2 是差不多的,相应改一下就行了
————————————————————————————————————————————
运行效果(程序运行的截图):