本文实例总结了C#子窗体与父窗体通信方法。分享给大家供大家参考。具体如下:
【第一种方法:】
第一步:
创建接口IForm,父窗体继承这个接口
?| 1 2 3 4 |
public interface IForm
{
void RefreshForm();
}
|
第二步:
父窗体实现接口中的方法,在实现接口的方法中写入刷新代码
?| 1 2 3 |
Form2 f = new Form2();
f.Owner = this;
f.ShowDialog();
|
第三步:
在子窗体中调用,刷新的方法
复制代码 代码如下: (this.Owner as IForm).RefreshForm();
【第二种方法:】
1.父窗体中定义刷新的方法RefreshForm()
2.在点击的事件Show出子窗体的时候,代码如下:
| 1 2 |
Form form=new Form();
form.Show(this);
|
3.在子窗体的点击事件中,代码如下:
复制代码 代码如下: (this.Owner as Form).RefreshForm();
【第三种方法:】
通过事件解决方法:
子窗体中定义:
| 1 2 |
public delegate void sendmessage(string message);
public event sendmessage SendTo ;
|
主窗体:
?| 1 2 3 4 5 |
ChildForm frm = new ChildForm();
frm.SendTo += new ChildForm.sendmessage(SendArgs);
frm.ShowDialog(this);
private void SendArgs(string Message)//主窗体接收消息
{MessageBox.Show( "主窗体已收到消息: " + Message);}
|
子窗体测试:
复制代码 代码如下: if (this.SendTo != null) this.SendTo( "主窗体收到了吗? ");
【第四种方法:】
通过引用:
下例演示怎样通过引用类型实现你的功能:
子窗体中定义:
新构造函数:
?| 1 2 3 4 5 |
public ChildForm(MainForm parent)
{
InitializeComponent();
this.ParentFrom = parent;//引用
}
|
主窗体中某Click:
?| 1 2 |
ChildForm frm = new ChildForm(this);
frm.ShowDialog(this);
|
子窗体测试:
?| 1 2 3 4 5 |
void ...Click(....)
{
this.Text = "测试引用 ";
if (this.ParentFrom != null) this.ParentFrom.Text += "- " + this.Text;//.......
}
|
希望本文所述对大家的C#程序设计有所帮助。








发表评论
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。