There are different ways to do it.
Please never name anything "Form1", "Label1", etc.; renamed all created types and members to some semantic names immediately. So, you want to have two forms:
AuthenticationForm
and
MainForm
.
One way is this:
partial class AuthenticationForm {
internal bool Authenticated { get { } }
}
partial class MainForm {
protected override void OnShown(EventArgs e) {
AuthenticationForm af = new AuthenticationForm();
af.ShowDialog();
if (!af.Authenticated)
Application.Exit();
}
}
Application.Run(new MainForm());
As the form
AuthenticationForm
is run in a modal form, the main form is shown but not accessible before the authentication procedure is complete, and
Application.Exit
guarantees that the main form will never be accessed if authentication is not successful.
This is pretty much standard way. Kim just posted an alternative answer where the main form is never shown. It requires modification of the main method (which is entry form).
The solution provided by Kim needs a fix (please see my comment to his solution). On way to fix it may be this:
partial class AuthenticationForm {
internal bool Authenticated { get { } }
}
static class Program {
[System.STAThread]
static void Main() {
AuthenticationForm af = new AuthenticationForm();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(af);
if (!af.Authenticated)
exit;
Application.Run(new MainForm());
}
}
—SA