如何在不创建新Form()的情况下从Form2访问Form1函数; [英] How to access Form1 Function from Form2 without creating new Form();

查看:76
本文介绍了如何在不创建新Form()的情况下从Form2访问Form1函数;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C#的新手

作为我现在面临的问题:

As the question I facing right now:

public void snz_btn_Click(object sender, EventArgs e)
        {
            this.Close();

//beside than this?
Form1 fs = new Form1();
fs.Snooze();

        }

除了使用Form1之外,fs = new Form1()会在我可以访问fs.Snooze()之前创建另一个新表单吗?因为这会使我的应用显示为2 Form1

Is that anyway other than using Form1 fs = new Form1() which create another new form before i can access fs.Snooze() ?? because this will make my apps appear 2 Form1

推荐答案

如果要访问Form1的现有实例,则需要以某种方式使该实例对Form2可用.

If you want to access an existing instance of Form1, you need to make that instance available to Form2 somehow.

常见的模式是为Form2提供构造函数,该构造函数将Form1的实例作为参数并存储该实例,例如作为字段或属性.

The common pattern is to provide a constructor for Form2 that takes an instance of Form1 as a parameter and stores that instance e.g. as a field or property.

private Form1 form1;
public Form2(Form1 form1)
{
    this.form1 = form1;
}

然后在构造Form2实例时

Then when constructing an instance of Form2

Form2 form2 = new Form2(someExistingForm1Instance);

这篇关于如何在不创建新Form()的情况下从Form2访问Form1函数;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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