[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: 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. }

This code creates a PasswordForm and displays it by calling its ShowDialog method. The ShowDialog call returns OK or Cancel depending on whether the user clicked the password form's OK button or the Cancel button.

The password dialog has a TextBox with PasswordChar set to X so you can't see what the user is typing. The form's CancelButton proerty is set to the Cancel button. If the user clicks that button, it automatically sets the form's DialogResult property to Cancel and hides the form.

If the user clicks the OK button, the following code executes.

// Validate the password. private void btnOk_Click(object sender, EventArgs e) { if (txtPassword.Text == "Secret") { // The password is ok. this.DialogResult = DialogResult.OK; } else { // The password is invalid. txtPassword.Clear(); MessageBox.Show("Inivalid password."); txtPassword.Focus(); } }

This code just compares the password entered by the user to the string "Secret." If the password matches, the code sets the password form's DialogResult property to OK. That hides the form and the main program's call to ShowDialog returns OK.

If the password is invalid, the program clears the password TextBox and displays an error message so the user can try again.

Of course in a real application, you shouldn't put the correct password in the code. It would be easy for a hacker to look in the code and find the password.

Download the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.