How can I close the 1st form without closing the full application?

Possible duplicate:
How do I close the login form and show the main form without closing my application?

How can I close the 1st form without closing the application?
FROM#. as an example, if my first form registers the form after entering the username and password, if they are correct, that the form should be closed and another form should be open.

I tried this.close()

but my complete app quits :( After that I tried it this.Hide()

, but my form still works, just hidden from the UI.



source to share

4 answers

It's actually pretty simple. In the main static method Program.cs, use the following code to start your LoginForm.

var myLoginForm = new LoginForm();


Then, from your LoginForm, just forget to run the following form before closing like this:

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



If you just want to close the app after logging in, follow these steps:



Hope it helps!



In your Program.cs you have to create an instance of the form you want to work on for a long time, not just the login form.

Then you can use another form to display the login form to get this information from the user, and when it exists, you will be returned to another form.



This is because the window you are closing is the main application window. Closing this window terminates the entire application.

Now here's the fix:

  • Create a second Form

    one LoginForm

  • In the main form's event handler (add one if not present), show LoginForm

    to ask the user for their credentials.

After verifying these credentials, you can either return from the event handler if the credentials are good, in which case the main window will appear and the application will start normally or close the main window and the entire application will be shut down.



When working with forms, you should understand that the call Application.Run()

simply switches the main application thread to the form UI thread. When the form calls Close (), it will complete any processing it needs and continue the call Application.Run()

. After that, you can run another one Application.Run()

in the next form if any property of your login form ( frmLogin.LoginSuccessful

or some such) is set.

However, this is not best practice (IMO). Instead, you have to open the login form to your main form, and then the main form will continue after you close the login form.



All Articles