2

I have two Win forms in my project, one Login form, and the Main form. I have a button in Login form, which when clicked should open the Main form and close the current(Login) form.

I have tried this method

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

But it only hides the current form. So even after I close the Main form, I have to manually stop debugging by pressing Shift + F5.

Then I have tried this following code

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

But now, when I click the button, the Mainform opens and within a second, both the forms are closed, and the program stops debugging.

How do I correctly open Mainform from Login form and I don't have to stop debugging ,manually ?

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
Akeel.F
  • 27
  • 2
  • 9

3 Answers3

0

You can achieve this way

private void button1_Click(object sender, EventArgs e)
  {
     Mainform frm = new Mainform();
     frm.Show();

     this.ShowInTaskbar = false;
     this.WindowState = FormWindowState.Minimized;
  }

and in another place you can show login form again

private void button1_Click(object sender, EventArgs e)
  {
     this.ShowInTaskbar = true;
     this.WindowState = FormWindowState.Normal;
  }
Mostafiz
  • 7,243
  • 3
  • 28
  • 42
0

Your problem is that you host Form2 inside Form1.

As it seems, your application begins with Form1, and in it you then load Form2, now you close Form1 and expect Form2 to stay alive when you just killed its host.

A better approach would be to initialize your application with a different form, or static class preferred, which will "last" during the lifetime of your application.

this is exactly why you get a class named Program.cs added to your solution, when you start a new Windows Form project.

Stavm
  • 7,833
  • 5
  • 44
  • 68
0

As @polisha989 said, you can host MainForm in Program.cs if you want terminate application when MainForm is closed or eventually reopen Loginform there.

2nd optoin is to pass reference of LoginForm to MainForm and reopen LoginForm while MainForm is closing.

3rd option is to call Application.Exit() while MainForm is closing. (find more here How to properly exit a C# application?

Community
  • 1
  • 1
David Pivovar
  • 115
  • 1
  • 10