How to press a button from another form using C#?

2019-02-26 03:23发布

I have 2 forms:

  1. Form1 that make a screenshot.
  2. Form2 that have 2 buttons to manipulate the screenshot created by form1.

Form1 also have a "hidden" button that contain the method to save the screenshot.

My questions:

How can i click the form1's button from form2? and How can i check when the form1 is closed and then close form2 too?

I've tried something like this but nothing happens when i click form2 save button:

var form = Form.ActiveForm as Form1;
if (form != null)
{
    form.button1.PerformClick();
}

标签: c# forms button
2条回答
Luminary・发光体
2楼-- · 2019-02-26 03:59

First of all the normal way multiple forms work is that when you close down the Startup form then the secondary forms will close also. If you are creating your Form2 in Form1 I would show it by using (your second Forms Instance).Show(this). You could then access the Form by Form2's Parent Property. i.e.

      var form = (Form1)this.Owner();

You should then be able to access all of the public methods of Form1, Also I would take the code that you are using to save your screenshot and put into a public method, no need to have it in a Button's click event especially if the button is hidden.

Here is a quick example:

Form1

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

    }

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

}

Form2

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

    private void button1_Click(object sender, EventArgs e)
    {
        var frm = (Form1)this.Owner;
        if (frm != null)
            frm.button1.PerformClick();
    }
}
查看更多
地球回转人心会变
3楼-- · 2019-02-26 03:59

Instead of making a hidden button just make a method not linked to a button.

In Form1.cs:

public void SaveScreenshot()
{
    //TODO: Save the Screenshot
}

In Form2.cs:

Form1 form = Application.OpenForms.OfType<Form1>().FirstOrDefault();
if (form != null) {
    form.SaveScreenshot();
}

Also make sure to declare the SaveScreenshot method as public or internal.

I changed the code that gets Form1. If you click a button on Form2 then Form2 will be the ActiveForm, so your code will never "see" Form1. I used LINQ methods in my code that will only work if you have a using System.Linq; at the top of your code.

查看更多
登录 后发表回答