Reputation: 41
I have a form1, from this form1 going to new form2, form2 new form 3... and when I close form1 then application close.but, i want close all form before close application.
Upvotes: 1
Views: 510
Reputation: 5890
Class System.Windows.Forms.Form has an event FormClosing. You can handle the closing of forms there.
In form1:
public void form1_FormClosing(object sender, FormClosingEventArgs e) {
form2.Close()
// if we have the instances of form3, form4 here, then:
// form3.Close()
// form4.Close()
}
In form2:
public void form2_FormClosing(object sender, FormClosingEventArgs e) {
form3.Close()
}
etc.
Upvotes: 0
Reputation: 70652
If I understand the question correctly (and I might not...it's hard to read), what you want is to ensure that closing your first form doesn't close the entire program, and that closing the last form does. If that's the case, then you need to make the following changes:
In your Program.cs file, you'll have some code that looks like Application.Run(new Form1());
. This passes a Form
instance to the Run()
method, and the Run()
method will automatically return and allow the program to exit when that Form
instance is closed.
Instead, don't pass anything to Run()
. Use the parameterless overload: Application.Run();
You will still have to create the first Form
instance and show it. E.g. before the call to Application.Run();
add this:
new Form1().Show();
Having done that, you now need to call Application.Exit()
when you actually want the program to end. So in your last form that you show, override OnFormClosed()
:
protected override voide OnFormClosed(FormClosedEventArgs e)
{
base.OnFormClosed(e);
Application.Exit();
}
If that's not what you wanted to do, please try to word your question more carefully and explain in more detail what you want.
Upvotes: 0
Reputation: 13669
you may try
foreach(Form f in Application.OpenForms)
{
f.Close();
}
you may adjust it as needed.
see more on Application.OpenForms
Upvotes: 2
Reputation: 199
just write this to show every form
Form1 f=new Form1();
f.ShowDialog();
Upvotes: 0