Good day to all. I have a question, i'm using wpf and i cant find the right way of closing the form1 from form2.
WpfForm form1 = new WpfForm();
form1.close();
Please i need help.
Good day to all. I have a question, i'm using wpf and i cant find the right way of closing the form1 from form2.
WpfForm form1 = new WpfForm();
form1.close();
Please i need help.
As Matt has stated you need to have a reference in your first form of you second form, so assuming that you will have that reference you can simply add an event handler like the one shown below at some point in your first form's code when the reference to the second form is set to an instance, something like your Window_Loaded event would be a good candidate.
secondWindow.Closing += (s, e) => this.Close();
The above is an inline event handler, if you'd rather have more verbose code you could do something like:
secondWindow.Closing += CloseMe;
private void CloseMe(Object sender, EventArgs e)
{
this.Close();
}
Incase you're interested, Mr. Skeet discusses inline event handler caveats in another question here.
You need a reference to your first form in your second. Then you can simply call close using that reference.
There are a few ways to handle it. You could add a property to your second form to hold a reference to your first form. When you create your second form, you will set that property and then in whatever the event in your second form is supposed to close the first form (e.g. clicking a button), you can use that reference to close the form.
As said Matt and Paulie you need have a reference in your first form, so if you would like do this without a reference you can use the static access modifier and delegates like here;
public delegate void Method();
private static Method close;
public Form1()
{
InitializeComponent();
close = new Method(Close);
}
public static void CloseForm()
{
close.Invoke();
}
Next in your second form you can close the first one without references writing simply this:
Form1.CloseForm();