Create a Login Form
I have a form that I want to provide some security on, but up to 开发者_JAVA技巧this point I've only created one form that does all of my work. I want to create a new form that pops up in front of my main form right when the application launches. Then validates the password entered against a MySQL database. I have all of the MySQL stuff down, but wondering how to make another form pop up in front of my main form which disables the main form, waits for the password form to validate, then disappears once the form is validated and lets the user perform their work. I'll also need to transfer the authenticated user's info back to my main form.
You can create a new form and then use the ShowDialog function. If you show the form from your main form it will be displayed in a modal fashion.
Create this in a login style and close the form if the user is authenticated or show an error if the username and password are incorrect.
From MSDN:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
I prefer to use ApplicationContext for this kind of log on form <--> shell form switching behavior.
Your main method:
public static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MyFancyContext());
}
And an implementation for MyFancyContext
:
public class MyFancyContext : ApplicationContext
{
private LogOnForm logOnForm;
private ShellForm shellForm;
public MyFancyContext()
{
this.logOnForm = new LogOnForm();
this.MainForm = this.logOnForm;
}
protected override void OnMainFormClosed(object sender, EventArgs e)
{
if (this.MainForm == this.logOnForm
&& this.logOnForm.DialogResult == DialogResult.OK)
{
// Assume the log on form validated credentials
this.shellForm = new ShellForm();
this.MainForm = this.shellForm;
this.MainForm.Show();
}
else
{
// No substitution, so context will stop and app will close
base.OnMainFormClosed(sender, e);
}
}
}
The MainForm
is the form that is currently receiving messages.
The advantage of this type of setup is that if you want to do things like hide the shell form after some idle timeout and redisplay the log on form, we have one class where this functionality takes place.
You can call showdialog(loginform) from the main form's constructor and return true if successful or change the startup for to the login form before the main form loads. Show dialog is modal.
精彩评论