您的位置:首页 > 编程语言 > C#

C#实现子窗体与父窗体通信方法实例总结

2015-09-17 18:02 2016 查看

本文实例总结了C#子窗体与父窗体通信方法。分享给大家供大家参考。具体如下:

【第一种方法:】

第一步:

创建接口IForm,父窗体继承这个接口

public interface IForm
{
void RefreshForm();
}

第二步:

父窗体实现接口中的方法,在实现接口的方法中写入刷新代码

Form2 f = new Form2();
f.Owner = this;
f.ShowDialog();

第三步:

在子窗体中调用,刷新的方法

(this.Owner as IForm).RefreshForm();

【第二种方法:】

1.父窗体中定义刷新的方法RefreshForm()
2.在点击的事件Show出子窗体的时候,代码如下:

Form form=new Form();
form.Show(this);

3.在子窗体的点击事件中,代码如下:

(this.Owner as Form).RefreshForm();

【第三种方法:】

通过事件解决方法:
子窗体中定义:

public delegate void sendmessage(string message);
public event sendmessage SendTo ;

主窗体:

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( "主窗体收到了吗? ");

【第四种方法:】

通过引用:

下例演示怎样通过引用类型实现你的功能:
子窗体中定义:

protected MainForm ParentFrom = null;//主窗体

新构造函数:

public ChildForm(MainForm parent)
{
InitializeComponent();
this.ParentFrom = parent;//引用
}

主窗体中某Click:

ChildForm frm = new ChildForm(this);
frm.ShowDialog(this);

子窗体测试:

void ...Click(....)
{
this.Text = "测试引用 ";
if (this.ParentFrom != null) this.ParentFrom.Text += "- " + this.Text;//.......
}

希望本文所述对大家的C#程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# 窗体 通信