C#中两个窗体之间的通信 [英] Communicate between two windows forms in C#

查看:34
本文介绍了C#中两个窗体之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种表格,一种是主表格,另一种是选项表格.例如,假设用户在主窗体上单击我的菜单:Tools ->选项,这会导致显示我的选项表单.

我的问题是如何将选项表单中的数据发送回主表单?我知道我可以使用属性,但我有很多选择,这似乎是一件 乏味 奇怪的事情.

那么最好的方法是什么?

解决方案

Form1 触发 Form2 打开.Form2 具有重载构造函数,它将调用 form 作为参数并提供对 Form2 成员的引用.这解决了通信问题.例如,我在 Form1 中将 Label 属性公开为 public,而在 Form2 中进行了修改.

通过这种方法,您可以以不同的方式进行交流.


(来源:
(来源:ruchitsurati.net)

I have two forms, one is the main form and the other is an options form. So say for example that the user clicks on my menu on the main form: Tools -> Options, this would cause my options form to be shown.

My question is how can I send data from my options form back to my main form? I know I could use properties, but I have a lot of options and this seems like an tedious odd thing to do.

So what is the best way?

解决方案

Form1 triggers Form2 to open. Form2 has overloaded constructor which takes calling form as argument and provides its reference to Form2 members. This solves the communication problem. For example I've exposed Label Property as public in Form1 which is modified in Form2.

With this approach you can do communication in different ways.

Download Link for Sample Project

//Your Form1

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 frm = new Form2(this);
        frm.Show();
    }

    public string LabelText
    {
        get { return Lbl.Text; }
        set { Lbl.Text = value; }
    }
}

//Your Form2

public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private Form1 mainForm = null;
    public Form2(Form callingForm)
    {
        mainForm = callingForm as Form1; 
        InitializeComponent();
    }

    private void Form2_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.mainForm.LabelText = txtMessage.Text;
    }
}


(source: ruchitsurati.net)


(source: ruchitsurati.net)

这篇关于C#中两个窗体之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆