It's because the lifetime of the application is linked to Form1. The Main method used to start the application shows this:
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
Application.Run
Holds up the main application thread for the lifetime of the Form1() object. If you close Form1 the thread exits and the process ends.
My advice would be add Form3 which is a controller for managing the forms. Set it to invisible but in the constructor load Form1 as a child to Form3.
Add an event to Form1 for when Form2 is required and use Form3 to also open Form2. Brief demo below:
public class Form3 : Form
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form3());
}
Form1 frm1;
Form2 frm2;
public Form3()
{
frm1 = new Form1();
frm1.OnOpenForm2 += new Form2.OnOpenForm(frm1_OnOpenForm2);
frm1.FormClosed += new FormClosedEventHandler(frm_FormClosed);
frm1.Show();
}
private void frm1_OnOpenForm2()
{
frm2 = new Form2();
frm2.FormClosed += new FormClosedEventHandler(frm_FormClosed);
frm2.Show();
}
void frm_FormClosed(object sender, FormClosedEventArgs e)
{
if(((Form)sender) == frm1)
frm1 = null;
if(((Form)sender) == frm2)
frm2 = null;
if(frm1 == null && frm2 == null)
Application.Exit();
}
}
public class Form1 : Form
{
public delegate void OpenForm2();
public event OpenForm2 OnOpenForm2;
}
In your project properties you'll have to change the start object to be Form3.
It's written off the top of my head, so if there are any problems or anything you don't understand, let me know.
As you're not displaying form 3, it's use could be called improper.
Application.Run
will also accepts an
ApplicationContext
class. For more information about
ApplicationContext
please see here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.applicationcontext.aspx[
^]