4

Possible Duplicate:
How can I close a login form and show the main form without my application closing?

How i can close a 1st form with out closing full the application?
C#. as a example if my 1st form is logging form after enter username and password if they are correct that form should be close and other form need to be open.

I tried this.close() but my full application is exiting :(. After that I tried this.Hide() it works but my form is still running just hidden from UI.

ty

Community
  • 1
  • 1
Rajika Nanayakkara
  • 658
  • 1
  • 6
  • 11
  • You can't. Don't use your login as a primary form, use it as a secondary form. You can open it, get credentials, then close it like normal. – Michael Todd Mar 09 '12 at 18:30

4 Answers4

9

It is actually quite simple. On your Program.cs Main static method use the following code to launch your LoginForm.

var myLoginForm = new LoginForm();
myLoginForm.Show();
Application.Run();

Then from your LoginForm, simply remember to launch your next Form before closing it like this:

var myNextForm = new NextForm();
myNextForm .Show();

this.Close();

If you rather just want to close the application after login fails just do the following:

this.close();
Application.Exit();

Hope it helps!

Reinaldo
  • 4,556
  • 3
  • 24
  • 24
0

In your Program.cs, you should have it create an instance of the form you wish to be long running instead of just the login form.

You can then have the other form display the login form to get that information from the user and when it exists you'll be back to your other form.

Brian Dishaw
  • 5,767
  • 34
  • 49
0

That is because the window you are closing is the main application's window. Closing that window will shut down the whole application.

Now here is the fix:

  1. Create a second Form, LoginForm for example
  2. On the main form load event handler (add one if there isn't any), show the LoginForm to ask the user to enter his/her credentials.

Once you check those credentials you can either return from the event handler if the credentials are good and in this case the main window will show up and the application will run normally or close the main window and the whole application will shut down.

GETah
  • 20,922
  • 7
  • 61
  • 103
0

When working with forms, what you have to realize is that calling Application.Run() just switches the applications main thread to the forms UI thread. When the form calls Close(), it will finish up whatever processing it needs to do and continues from the Application.Run() call. What you can do after this is run another Application.Run() on the next form if some property of your login form is set (frmLogin.LoginSuccessful or some such).

However, this is not best practice (IMO). What you should do is instead have the login form opened from within your main form, and then the main form will continue to run after the login form closes.

SPFiredrake
  • 3,852
  • 18
  • 26