您的位置:首页 > 编程语言 > C#

C#使用委托从子窗体向主窗体发送消息

2017-05-11 07:53 465 查看
C#经常会使用到窗体的交互,需要共享数据

/*

* 【1】申明委托(定义一个函数原型:返回值,参数类型和个数)

* 【2】根据委托,定义一个目标方法(目标方法可以有多个),注意目标方法和委托的返回值以及参数类型个数必须保持一致

* 【3】创建委托对象,关联目标方法

* 【4】通过委托来调用方法,而不是直接使用方法

*/

主窗体代码:

public delegate void GetExposeTimeDelegate(string count);//【1】

public partial class MainForm : Form

{

public MainForm()

{

InitializeComponent();

ChildForm objectChildForm = new ChildForm();

objectChildForm.objectGetExposeTimeDelegate += GetExposeTime;//【3】

objectChildForm.Show();

}

public void GetExposeTime(string count)//【2】

{

lblCount.Text = count;

}

}

子窗体代码:

public ChildForm()

{

InitializeComponent();

}

public string strCount;

public GetExposeTimeDelegate objectGetExposeTimeDelegate;//【3】委托变量,作为传递信息的桥梁

private void numericUpDown1_ValueChanged(object sender, EventArgs e)

{

strCount = Convert.ToString(ExposeTimeCount.Value);

objectGetExposeTimeDelegate(strCount);//【4】

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: