I know that I can hijack a form by showing a login form in an event prior to that form displaying (Load() event, IIRC), but in (perhaps foolishly) trying to “cut corners” and create a quick&dirty login screen, I’ve run into a dilemma.
Here’s what I did with an existing project (login form added after the fact):
1) Created the login form
2) Changed program.cs so that this login form is now the first form created
3) Added code to the login form that shows the "main" form if the login is successful. I then Hide the login form.
This caused the app to never shut down (except via Shift+F5) as the hidden main form was still lurking about. So, I added a “Close()” to the “main” form’s FormClosing event, thinking this would cause the whole app to shut down (IOW, the Hidden login form).
But (fittingly, perhaps), rather than solving my problem, this causes “An unhandled exception of type ‘System.StackOverflowException’ occurred in System.Windows.Forms.dll”
Now I don’t know if I should proceed with this quick&dirty attempt (and how) or cut my losses and revert to the show-the-login-form-in-the-Load-event method[ology].
UPDATE
Alex M’s solution worked. The only additional thing you need to do is something like this in your login form:
private void buttonLogin_Click(object sender, EventArgs e)
{
String userName = textBoxUserName.Text.Trim();
String pwd = textBoxPassword.Text.Trim();
if ((userName == "donMcLean") || (pwd == "Drove my Chevy to the levee but the levee was dry, them good ole boys were drinking whiskey & Rye"))
{
this.DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("Incorrect User Name and/or Password");
}
}
The creation order is not particularly important. You can show login form using
form.ShowDialog(). Doing so disposes the form and addresses the issue you are describing.For example: