ssturges
ssturges

Reputation: 47

How to close C# program, from the second form (not hide) C# Multiform issue

Problem: I have created a program that has two forms. When a button is pressed on Form1, the program "hides" Form1 and "shows" Form2. The issue is, when I close Form2, the program continues to run in the background, I believe this is because the program needs Form1 to be closed, not hidden in order for the program to end.

My Question is how do I override the Second Form to close the program and not hide?

    private void btnCreate_Click(object sender, EventArgs e)
    {
        Form2.Show(); 
        Form1.Hide();
    }

I know I could show Form1 again from Form2, and then close, but I would really like to avoid that.

Upvotes: 2

Views: 13447

Answers (3)

albertdadze
albertdadze

Reputation: 59

In application development especially for winforms for the sake of your users, always have a main form (whether an mdiparent or a single parent) that will always be the main form that all other forms show from.

Giving an answer to the question will be encouraging bad programming practice.

Let the mainform close and the application will end. Hiding form1 will not end the application.

Upvotes: 0

Adriano Repetti
Adriano Repetti

Reputation: 67128

You have few options to do that, according to how your application is.

First and intuitive solution is to call Close() instead of Hide() for Form1. This works only if Form1 is not the main form of your application (the one inside main message loop started with Application.Run()).

Second solution is to add an event handler for the FormClosed event of Form2 and to close first form when second one is closed:

private void btnCreate_Click(object sender, EventArgs e)
{
    Form2.Show();
    Form2.FormClosed += new FormClosedEventHandler(delegate { Close(); });
    Form1.Hide();
}

You can directly close Form1 or call Application.Exit() (in case you did open multiple forms you want to close all together).

Last solution is to make second form the owner of first one:

private void btnCreate_Click(object sender, EventArgs e)
{
    Form2.Show();
    Form1.Owner = Form2;
    Form1.Hide();
}

This will close automatically the owned form when owner is closed. This is the solution I prefer but it works only for one form (an owner can own only one form).

Upvotes: 9

Daniel Gielow Junior
Daniel Gielow Junior

Reputation: 356

You can use the FormClosed event:

    private void btnCreate_Click(object sender, EventArgs e)
    {
        Form2.Show();
        Form2.FormClosed += new FormClosedEventHandler(form2_FormClosed);
        Form1.Hide();
    }

    void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        Form1.Close();
    }

Upvotes: 3

Related Questions