首 页最新软件下载排行文章资讯投稿发布下载专题
维维下载站
您的位置:首页编程开发网络编程编程其它 → C#实现子窗体与父窗体通信方法例子详解

C#实现子窗体与父窗体通信方法例子详解

来源:维维整理 发布时间:2015-9-18 8:08:49 人气:

C#实现子窗体与父窗体通信方法例子详解,本文总结了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;//....... 
}
相关下载
栏目导航
本类热门阅览