Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

winforms

I have two forms in my project (Login and Main).

What I'm trying to accoomplish is, if the login is successful, I must show the Main form and close the Login form.

I have this method in Login form that closes the Login form when the login is successful. But the Main form doesn't show.

public void ShowMain() {     if(auth()) // a method that returns true when the user exists.     {                      var main = new Main();         main.Show();         this.Close();     }     else     {         MessageBox.Show("Invalid login details.");     }          } 

I tried hiding the Login form if the login process is successful. But it bothers me because I know while my program is running the login form is still there too, it should be closed right?

What should be the right approach for this? Thanks...

like image 544
yonan2236 Avatar asked Jan 21 '11 13:01

yonan2236


People also ask

How do I close a login form?

You should use a using keyword while opening a Login form, and a ShowDialog() method; wihch will close the form it self if the login is successful.

How do I close an application in Windows form?

Exit() Informs all message pumps that they must terminate, and then closes all application windows after the messages have been processed.


1 Answers

The reason your main form isn't showing is because once you close the login form, your application's message pump is shut down, which causes the entire application to exit. The Windows message loop is tied to the login form because that's the one you have set as the startup form in your project properties. Look in your "Program.cs" file, and you'll see the responsible bit of code: Application.Run(new LoginForm()). Check out the documentation for that method here on MSDN, which explains this in greater detail.

The best solution is to move the code out of your login form into the "Program.cs" file. When your program first starts, you'll create and show the login form as a modal dialog (which runs on a separate message loop and blocks execution of the rest of your code until it closes). When the login dialog closes, you'll check its DialogResult property to see if the login was successful. If it was, you can start the main form using Application.Run (thus creating the main message loop); otherwise, you can exit the application without showing any form at all. Something like this:

static void Main() {     LoginForm fLogin = new LoginForm();     if (fLogin.ShowDialog() == DialogResult.OK)     {         Application.Run(new MainForm());     }     else     {         Application.Exit();     } } 
like image 117
Cody Gray Avatar answered Oct 11 '22 20:10

Cody Gray