Rhino
Rhino

Reputation: 45

Closing an unrelated .NET form inside another form in Winforms

I am trying to understand the behavior of the following code in a WinForms application.
I have two forms - Form1 and Form2. When i close Form1 from inside Form2, even Form2 gets closed. I have ensured that they both have the Owner property set to null.

Can anyone explain why Form2 gets closed as well from the code below?
Form1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
}

Form2:

public partial class Form2 : Form
{
    Form1 f1;
    public Form2(Form1 f1)
    {
        InitializeComponent();
        this.f1 = f1;
    }

    private void button1_Click(object sender, EventArgs e)
    {          
        f1.Close();         
    }
}

Program.cs

static void Main()
    {           
        Form1 f1 = new Form1();
        f1.Size = new Size(0, 0);
        f1.Show();           

        Form2 f2 = new Form2(f1);
        f2.ShowDialog();            

        Application.Run(new MainForm());
    }

When the Button on Form2 is clicked both Form1 and Form2 get closed. I have also ensured that the button is not the okbutton or cancelbutton for Form2. Can anyone explain why this happens?

Upvotes: 0

Views: 96

Answers (1)

tozlu
tozlu

Reputation: 4865

Form1 closes because you have created a new Form1 and passed it to Form2, and inside Form2, you are closing the Form1. And just because Form2 is a DialogForm, and created after Form1, it is supposed as a DialogForm of Form1, so if Form1 is closed, the DialogForm is closed too. It is an expected behaviour rather than a quirky one.

Either show it using

f2.Show();

or show the Form2 dialog form inside MainForm (by passing f1 to Form2 via MainForm), so Form1 closes but not Form2.

Update:

Try this in your Program.cs and you will see that Application's MainWindow is closed after you close Form1.

Form1 f1 = new Form1();
f1.Size = new Size(0, 0);
f1.Show();

MessageBox.Show(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle.ToString());

Form f2 = new Form2(f1);

MessageBox.Show(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle.ToString());

f2.ShowDialog();

MessageBox.Show(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle.ToString());

Application.Run(new MainForm());

Upvotes: 1

Related Questions