Danial Ahmed
Danial Ahmed

Reputation: 866

Form1 hides instead of closing

I am trying to create a simple login page on which if i click login button form1 should hide and form2 should popup and on form2 when i click logout it should bring me back to form1, problem is that when i click logout button on form2 it brings me back to form1 like it should but when i click "X" (Close) on form1 it hides (I can see the application running in task manager) instead of closing.

form1 sign in button code:

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

form2 logout button code:

private void button1_Click(object sender, EventArgs e)
    {
        Form1 loginPage = new Form1();
        loginPage.Show();
        this.Close();
    }

Upvotes: 1

Views: 78

Answers (2)

Willy David Jr
Willy David Jr

Reputation: 9151

The problem is here, you are creating a new instance of Form1 instead of opening it again:

Form1 loginPage = new Form1();

Here try this one:

private void button1_Click(object sender, EventArgs e)
{
    var formToBeOpen = Application.OpenForms.OfType<Form1>().SingleOrDefault();
    formToBeOpen.Show();
    this.Close();
}

Now regarding your post, that if you close your Form2, your Form1 is still running on the background, because of this code:

this.Hide();

You just hide it, then open your Form2, then you click the X button on your Form2 which closes your Form2 but not necessarily mean will close your Form1 as well, since it's still running on the background. If you want to close your Form1, add this on your Form2 code:

private void Form2_FormClosed(object sender, FormClosedEventArgs e)
{
    var formToBeOpen = Application.OpenForms.OfType<Form1>().SingleOrDefault();
    formToBeOpen.Close();
}

Upvotes: 3

chopperfield
chopperfield

Reputation: 567

i'll try to answer. because you declare a new instance in button logout. in form1 button put this code

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

as form2, since i pass form1, put this code

public partial class Form2 : Form
{
    Form form1;
    public Form2(Form x)
    {
        InitializeComponent();
        form1 = x;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.Hide();
        form1.Show();
    }
}

Upvotes: 0

Related Questions