Bitterblue
Bitterblue

Reputation: 14085

C# - How Do I Close Main Form Together With Child Forms (while child windows must close ONLY when main form is closing)

I have a main window and a few child windows. Child windows contain some data so I don't want them to be closed. So I hide them while in FormClosing I set e.Cancel = true;

But when I want the main window to close (exit application). I have some trouble to exit it. First it wouldn't close. But with an extra variable to note that I'm closing I need 2 clicks to actually close it (problem is before onFormClosing(mainWIndow, ...) is executed the framework tries to close the children which will hide themselves first).

// main and child windows have this as form closing event proc
private void onFormClosing(object sender, FormClosingEventArgs e)
{
    if (sender == this) // main
    {
        exitApp = true;
    }
    else
        if (sender == formChild) // child
        {
            if (!exitApp)
            {
                e.Cancel = true;
                formChild.Hide();
            }
        }
}

How can I close them all in 1 click ?

I would also like to avoid Application.Exit(); because I need to make sure all threads close properly. So best would be a clean close.

Upvotes: 0

Views: 1047

Answers (2)

Bitterblue
Bitterblue

Reputation: 14085

Found the solution myself:

// ...
if (sender == this) // main
{
    exitApp = true;
    FormClosing -= onFormClosing;
    Close();
}
// ...

Upvotes: 0

icbytes
icbytes

Reputation: 1851

You can force the application with Application.Exit().

Upvotes: 1

Related Questions