C#通过委托与事件实现多个子窗体向父窗体传数据
按照5个步骤实现:
父窗体:
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 EventDemo0731
{
//【1】声明委托
public delegate void delegateSendMsg(string msg);
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
Client1 client1 = new Client1();
Client2 client2 = new Client2();
//【5】关联事件
client1.SendMsgEvent += new delegateSendMsg(this.EventResponse);
client2.SendMsgEvent += new delegateSendMsg(this.EventResponse);
client1.Show();
client2.Show();
}
//【4】事件响应方法
public void EventResponse(string msg)
{
tb_Msg.Text = msg;
}
}
}
子窗体1:
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 EventDemo0731
{
public partial class Client1 : Form
{
//【2】定义事件
public event delegateSendMsg SendMsgEvent;
public Client1()
{
InitializeComponent();
}
private void bt_Send_Click(object sender, EventArgs e)
{
//【3】激发事件
SendMsgEvent("【客户端1】" + tb_Msg.Text.Trim());
}
}
}
子窗体2:
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 EventDemo0731
{
public partial class Client2 : Form
{
//【2】定义事件
public event delegateSendMsg SendMsgEvent;
public Client2()
{
InitializeComponent();
}
private void bt_Send_Click(object sender, EventArgs e)
{
//【3】激发事件
SendMsgEvent("【客户端1】" + tb_Msg.Text.Trim());
}
}
}
运行结果如下:
版权声明:本文为qq_43024228原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。