Application remains open when using Owner.Show () for the main form

I have two forms, the main and the second form. Since I want to easily move between them, while avoiding creating multiple instances of each of them, I used this in the main form :

Form2 secondForm = new Form2();
private void btnForm2_Click(object sender, EventArgs e)
{
 secondForm.Show(this);
 Hide();
}

and the code below in the second form :

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{ 
 e.cancel = true;
 Owner.Show();
 Hide();
}

Everything works just fine, except that I cannot close the application. When I move to the second form and return to the main one, the close button will not work.

How can I close the program while I am still using this code?

I also tried this code to see if the close button works:

 private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
      MessageBox.Show("Closing");
 } 

MessageBox was shown, but nothing happened after.

+4
4

, - e.cancel = true. , .

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
 {
     System.Windows.Forms.Application.Exit();
 } 

2 , :

void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
 //close button click by user on form 2
    if(e.CloseReason == CloseReason.UserClosing)
        e.cancel = true //cancel event
   else
     e.cancel = false //close this form
}

CloseReason.UserClosing, . :

 void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {

//check if closing signal is from parent
       if   (e.CloseReason == CloseReason.UserClosing.FormOwnerClosing)
         e.cancel = false //close this form
      else 
          e.cancel = true 
    }
0

Environment.Exit(0);

+3

1 "" 2. Form2_Closing, 1.

( ), Form2. , / .

    private void btnForm2_Click(object sender, EventArgs e)
    {

        secondForm.FormClosing += secondForm.Form2_FormClosing;
        secondForm.Show(this);
        Hide();
    }

    internal void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;



        FormClosing -= Form2_FormClosing;
        Owner.Show();
        Hide();
    }

, FormClosingEventArgs.CloseReason :

private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (e.CloseReason == CloseReason.FormOwnerClosing) { return; }
        e.Cancel = true;
        Owner.Show();
        Hide();


    }
0

.

Form1_FormClosing :

secondForm.Close();

. Form2_FormClosing , :

if (this.Visible)
{
    ...
}

. , , 2 , .

, Environment.Exit(0); , . winforms - #? - . MSDN, . , - . . Application.Exit() vs Application.ExitThread() vs Environment.Exit(). Environment.Exit, Application.ExitTread Application.Exit, Application.Exit . , , , .

0

All Articles