委托在子窗体和父窗体之间交换数据的应用

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;

//form1:
//委托方式子窗口和父窗口交换数据
namespace WindowsFormsApp1
{

public delegate void ShowMessageService(string msg);//定义一个委托
public partial class Form1 : Form
{

private Form2 childForm = new Form2 ();  //new 子窗体
public Form1()
{
InitializeComponent();
}


private void Form1_Load(object sender, EventArgs e)
{

childForm.showMessageChild = new ShowMessageService(UpdateLabel1); //定义委托实例,指定子窗体的委托是showMessageChild,发过来的数据由UpdateLable处理
childForm.Show();


}

public void UpdateLabel1(string msg)
{

this.textBox1 .Text = msg;
}

private void button1_Click(object sender, EventArgs e)
{

ShowMessageService sms = new ShowMessageService(childForm.UpdateLabel2); //定义一个委托 ,指定由子窗体的updateLable2处理
this.BeginInvoke(sms, textBox1 .Text);

}
}
}

 

 

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;


//form2:
//委托方式子窗口和父窗口交换数据
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{

public ShowMessageService showMessageChild;
public Form2()
{
InitializeComponent();
}

private void Form2_Load(object sender, EventArgs e)
{

}
public void UpdateLabel(string msg)
{

this.textBox1 .Text = msg;
}

private void button1_Click(object sender, EventArgs e)
{

this.BeginInvoke(showMessageChild, textBox1 .Text );

 

}
}
}

 

posted @ 2020-08-10 14:50  Jiangxuhua  阅读(46)  评论(0)    收藏  举报