I have a WinForms application, with a login form and main form. The login form contains two textboxes for the user to enter credentials, an OK button, and a Cancel button. The following code is the event handler for the OK button:
private void button_OK_Click(object sender, EventArgs e)
{
if (authenticated())
{
this.Close();
Application.Run(new MainWindow());
}
else
{
MessageBox.Show("Incorrect credentials", "Retail POS", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
The problem with this is that it keeps the login dialog when the main form opens. I have tried to accomplish the desired behaviour by showing the login form as a modal dialog by calling ShowDialog() from Program.cs, but this has not achieved the desired behaviour.
Note that the main form has an option to log out. That is, it should remove the main form and display the login form again.
Program.cs code:
static void Main()
{
LoginForm loginForm = new LoginForm();
loginForm.ShowDialog();
}
This produces an error, saying a second message loop cannot be started.
You need to hide your fist from. You can do it with
this.Hide()Be careful where you position
this.Hide().If you are using
mainForm.Show();you can place it before or after it, but if usingmainForm.ShowDialog();you can place it only before it sinceShowDialog()stops code from executing until form which called this method is closed.From
program.csyou start your application withApplication.Run(YourMainForm)Since you want your
LoginFormto be first when you open app you should create it insideProgram.csand pass it insideApplication.Run()like this:Now we have
LoginFormdisplayed. We can not close it since our application will close (since it is main form)So when user login and press button and succeed, we hide our main form and show other we want like this:
Now we have our
MainFormdisplayed, and login hidden.Since you want to make so user can log off, you can do it two ways:
First is when user press button, we do this:
This way we again display Login Form (at this point we have 2 login forms in memory, main one and new one which is a waste of memory) and there user can login again. This way every time user logs out you will have one more
LoginFormin memory which is very bad.Other efficient way is that inside
Program.csfile we do not createLoginForminstance insideMain()function, but outside and mark it aspublic staticIt would look like this:
Now when we have this and user press
Logoutin yourMainWindowyou do not need to create new instance ofLoginFormbut you can justShow()existing (main) one withProgram.mainForm.Show()