加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 06:00:17 所属栏目:百科 来源:网络整理
导读:本文实例总结了C#子窗体与父窗体通信方法。供大家参考研究。具体如下: 【第一种方法:】 第一步: 创建接口IForm,父窗体继承这个接口 public interface IForm{ void RefreshForm();} 第二步: 父窗体实现接口中的方法,在实现接口的方法中写入刷新代

本文实例总结了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#程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读