BLOG.CSHARPHELPER.COM: Display a simple password dialog before a program starts in C#
Display a simple password dialog before a program starts in C#
You might think that a program could start with a password form and then display its main form if the user enters a valid password. Unfortunately when the initial password form closes, it ends the whole application.
A better approach is to make the main form be the startup form. It's Load event handler displays the password form. If the user successfully enters the password, the program continues as normal. If the user fails to enter the password, the main form closes itself and the program ends.
The following code shows the main form's Load event handler.
// Display the password form. private void Form1_Load(object sender, EventArgs e) { // Display the password form. PasswordForm frm = new PasswordForm(); if (frm.ShowDialog() != DialogResult.OK) { // The user canceled. this.Close(); }
// Otherwise go on to show this form. }
The Password dialog has a TextBox with PasswordChar set to X so you can't see what the user is typing. If the user clicks the Cancel button, the dialog returns Cancel and the main form closes.
If the user clicks the OK button, the dialog validates the password (in this example, it should be "Secret"). If the password is valid, the dialog returns OK and the program continues as usual. If the password is invalid, the dialog displays an error message and lets the user try again.
Comments