当打开两个窗体时,如何在Form1上使用Button2上的Button运行Button1.PerformClick()

时间:2014-08-16 22:58:28

标签: c#

我有2个Form,我希望在form1中运行Button1.PerformClick(),在form2中使用button2,当打开两个表单时!

我不想创建一个实例Form1。

谢谢朋友们

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

    private void buttonShowForm2_Click(object sender, EventArgs e)
    {
        Form2 F2 = new Form2();
        F2.ShowDialog();
    }

    private void button1_Click(object sender, EventArgs e)
    {
         //Run my method...
    }
}



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

    private void ClickButton1Form1_Click(object sender, EventArgs e)
    {
        Form1 //Run my method... |Form1.Button1.PerformClick() 

    }

}

1 个答案:

答案 0 :(得分:0)

Form2需要对Form1实例的引用,并且需要调用该实例上的功能。

Form1上创建一个调用此功能的方法:

public void PerformButton1Click()
{
    Button1.PerformClick();
}

Form1的构造函数需要Form2的实例:

private Form1 Form1Instance { get; set; }

public Form2(Form1 form1Instance)
{
    InitializeComponent();
    Form1Instance = form1Instance;
}

在构造Form2的实例时传递对现有实例的引用:

Form2 F2 = new Form2(this);
F2.ShowDialog();

然后您可以在该实例上调用该功能:

private void ClickButton1Form1_Click(object sender, EventArgs e)
{
    Form1Instance.PerformButton1Click();
}