I have 2 forms:
Form1 also have
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();
}
}
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.