窗体结构

第一,主窗体项目
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 ReceivemasgDelegate
{
public partial class mainfrm : Form
{
/// <summary>
/// 系统无参构造函数
/// </summary>
public mainfrm()
{
InitializeComponent();
}
/// <summary>
/// 主窗体群发委托
/// </summary>
public Action<string, string> sendmsg = null; //创建委托变量sendmsg
/// <summary>
/// 子窗体集合
/// </summary>
private List<childfrm> OtherForms = new List<childfrm>();
/// <summary>
/// 声明子窗体实例
/// </summary>
public childfrm otherfrm = null;
/// <summary>
/// 主窗体收消息方法
/// </summary>
/// <param name="msg"></param>
/// <param name="frmname"></param>
private void ReceviedMsg(string msg, string frmname)
{
this.tbReceiveMsg.Text += "\r\n 来自:" + frmname + "消息:" + msg;
}
/// <summary>
/// 创建子窗体按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnaddfrm_Click(object sender, EventArgs e)
{
for (int i = 1; i < 5; i++)
{
otherfrm = new childfrm("子窗体:" + i);
sendmsg = otherfrm.ReceviceFrmMsg;
otherfrm.Show();
OtherForms.Add(otherfrm);
otherfrm.RecevieMsgDelegate = ReceviedMsg;
}
}
/// <summary>
/// 主窗体群发消息按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnsendMsg_Click(object sender, EventArgs e)
{
foreach (var form in OtherForms)
{
sendmsg = form.ReceviceFrmMsg; //foreach 循环在子窗体集合中取出每个窗体,并调用子窗体的接受方法
this.sendmsg(this.Text.Trim(), this.tBSendMsg.Text.Trim());
}
}
}
}
第二,子窗体项目
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 ReceivemasgDelegate
{
public partial class childfrm : Form
{
/// <summary>
/// 系统无参构造函数
/// </summary>
public childfrm()
{
InitializeComponent();
}
/// <summary>
/// 系统委托
/// </summary>
public Action<string, string> RecevieMsgDelegate=null; //声明系统委托变量RecevieMsgDelegate
/// <summary>
/// 有参构造函数
/// </summary>
/// <param name="frmname">子窗体名称参数</param>
public childfrm(string frmname )
{
InitializeComponent();
this.Text = frmname;
}
/// <summary>
/// 委托方法
/// </summary>
/// <param name="mainfrmname"></param>
/// <param name="mainfrmmsg"></param>
public void ReceviceFrmMsg(string mainfrmname ,string mainfrmmsg)
{
this.textBox2.Text += "\r\n 来自:"+mainfrmname+ "广播消息:"+mainfrmmsg;
}
/// <summary>
/// 发送消息事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnsendMsg_Click(object sender, EventArgs e)
{
RecevieMsgDelegate(this.textBox2.Text.Trim(), this.Text.Trim());
}
}
}