Search code examples
c#formsformclosing

How do I prevent a Form from opening multiple times in C#, while keeping a connection to the parent Form that came before it?


private void button4_Click(object sender, EventArgs e)
    {
        LogoutQuestion log = new LogoutQuestion(this);
        log.Show();
    }

This is the code in the Menu Form. Basically what I want to do is to ask the user if he wants to leave the program, and if so to close the LogoutQuestion Form and the parent, Menu Form. Any ideas on how to accomplish that?

namespace Project
{
public partial class LogoutQuestion : Form
{
    Form FormParent = null;
    public LogoutQuestion(Form parent)
    {
        FormParent = parent;
        InitializeComponent();
    }

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

    private void button2_Click(object sender, EventArgs e)
    {
        this.Close();
    }
}

}

The above is the whole LogoutQuestion Form I spoke of. Any help will be greatly appreciated. :-)


Solution

  • Make LogoutQuestion a dialog(log.ShowDialog();) This way you can also retrieve the result of the users response, since this will return a DialogResult.

    With ShowDialog you make the form modal. This means that it is tied to the parent form that showed it. This is just like when you try to save a file in other windows programs. This also means that the user can't proceed with anything else, until this form is closed. This also gives you the option to use the results of the users actions when the form closes.

    private void button4_Click(object sender, EventArgs e)
    {
        LogoutQuestion log = new LogoutQuestion();
        DialogResult dr = log.ShowDialog();
        if(dr != DialogResult.Cancel)
        {
            this.Close();
        }
    }