zoukankan      html  css  js  c++  java
  • 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;//....... 
    }
  • 相关阅读:
    14、python基础
    13、Python入门
    12、运算符、流程控制
    10、Linux(六)
    Windows 分层窗口 桌面上透明 Direct3D
    Windows 进程间通信 共享内存
    Linux 库的使用
    FFmpeg 命令行
    FFmpeg 摄像头采集
    FFmpeg input与output 函数流程
  • 原文地址:https://www.cnblogs.com/yc1224/p/14024889.html
Copyright © 2011-2022 走看看