I have 2 forms:
- Form1 that make a screenshot.
- 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();
}
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
inForm1
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.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
Form2
Instead of making a hidden button just make a method not linked to a button.
In
Form1.cs
:In
Form2.cs
:Also make sure to declare the
SaveScreenshot
method aspublic
orinternal
.I changed the code that gets
Form1
. If you click a button onForm2
thenForm2
will be theActiveForm
, so your code will never "see"Form1
. I used LINQ methods in my code that will only work if you have ausing System.Linq;
at the top of your code.