I have 2 Forms, Startform is a Login Form (Form1) and a Form that opens after Login, Form2.
when Login is successful the form2 shows.
f2.Show(); //form2 show
this.Hide(); //login(f1) hide
This works.
Now i want that if i press the red X Button (right top) that Form2 close and the Login page shows again.
I tried this in Form2:
Form1 f1 = new Form1();
....
...
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
f1.show();
}
But this just close the Form2 and not open the From1 and the Program is still running in the Background
In my example Form1
does role of your LoginForm
problem is what you are killing a Form2
which actually have created instance of Form1
(here your login form). so when instance of Form2
will be gone with it all its local instance will be gone too.
you can do one thing, while creating an object of Form2
from you Form1
pass object of Form1
to Form2
.
so you will not required to create an instace of Form1
in Form2
and while closing it you can simply call Form1
's show method.
like below.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//passing current class' object
Form2 form2 = new Form2(this);
form2.Show();
this.Hide();
}
}
and Form 2 :
public partial class Form2 : Form
{
Form1 m_form1;
public Form2(Form1 form1)
{
InitializeComponent();
m_form1 = form1;
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
m_form1.Show();
}
}