Tuesday, June 7, 2011

Login and Main Forms

Many Windows Forms Developers are confused about a simple Use Case.

The use case is:
- User starts an application.
- Login Form appears.
- Application Exists if the user closes the Login Form.
- Upon successful login the Login Form closes and the Main Form of the application shows.
- Application Exists if the user closes the Main Form.

Many developers suggests complex implementations including deriving from the ApplicationContext and use the derived class in an overload to the Application.Run() method.
Examples of what have been discussed:
http://stackoverflow.com/questions/1629205/windows-forms-create-the-main-application-after-login-which-form-to-run
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/73aeabe3-42db-4747-b3c7-9a5e4ea393ac/
http://www.codeproject.com/KB/cs/applicationcontextsplash.aspx

The implemntation can be much easier than this.
The ide is to open the Login Form as a modal dialog in the MainForm Load event.
And close the main form if the result was not OK.

Try this:

Here is the entry point (nothing done here):
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}

Login Form:
public partial class LoginForm : Form
{
private bool _authenticated = false;

private void _loginBtn_Click(object sender, EventArgs e)
{
if (AUTHENTICATION LOGIC)
{
_authenticated = true;
this.Close();
return;
}

MessageBox.Show("Login Failed", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}

private void LoginForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (_authenticated)
this.DialogResult = DialogResult.OK;
else
this.DialogResult = DialogResult.Abort;
}
}

Main Form:
public partial class MainForm : Form
{
private void MainForm_Load(object sender, EventArgs e)
{
var loginForm = new LoginForm();
if (loginForm.ShowDialog() != DialogResult.OK)
{
this.Close();
}
}
}


That's it.