Click here to Skip to main content
15,896,118 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
problem is:form1 is parent and form2 is child.
so when i close form1,form2 will close automatically.
how to change parent and child forms to each other?
Posted

1 solution

It's because the lifetime of the application is linked to Form1. The Main method used to start the application shows this:

C#
[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:

C#
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[^]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900