一 显示效果
二 代码
1 程序入口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ParentFrm parentFrm = new ParentFrm();
Application.Run(parentFrm);//启动父窗体
}
}
}
2 接口
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public interface InterfaceObserver
{
TextBox getTextBox();
}
}
3 父窗口
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class ParentFrm : Form, InterfaceObserver
{
public ParentFrm()
{
InitializeComponent();
}
public TextBox getTextBox()
{
return this.TbParent;//TbParent 是私有的对象 ,所以要有公有的方法获取TbParent对象
}
private void button1_Click(object sender, EventArgs e)//点击事件
{
ChildFrm childFrm = new ChildFrm();
ChildForm1 childForm1 = new ChildForm1();
childFrm.Show();//显示子窗体
childForm1.Show();//显示子窗体1
childFrm.ListObserver.Add(this); //建立父子关系
childFrm.ListObserver.Add(childForm1);//建立兄弟关系
}
}
}
4 子窗口
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 WindowsFormsApplication1
{
public partial class ChildFrm : Form
{
public List<InterfaceObserver> ListObserver { get; set; }
public ChildFrm()
{
InitializeComponent();
this.ListObserver = new List<InterfaceObserver>();
}
private void TbChild_TextChanged(object sender, EventArgs e)
{
foreach( InterfaceObserver IObserve in ListObserver)
{
IObserve.getTextBox().Text = this.TbChild.Text;//接口(InterfaceObserver)实现多态,将输入的信息同步至其他的窗口
}
}
}
}
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 WindowsFormsApplication1
{
public partial class ChildForm1 : Form, InterfaceObserver
{
public TextBox getTextBox()
{
return this.textBox1;
}
public ChildForm1()
{
InitializeComponent();
}
}
}