You can set
AcceptButton[
^] and
CancelButton[
^] property the button in your Form that handles the default Enter and ESC action.
AcceptButton and CancelButton property makes sense when used with Form.ShowDialog().
Remember that just setting the AcceptButton/CancelButton is not enough. This just tell which button should be invoked on ENTER/ESC. We have to set the DialogResult in the Button handler.
button1.DialogResult = System.Windows.Forms.DialogResult.OK;
button2.DialogResult = System.Windows.Forms.DialogResult.Cancel;
form1.AcceptButton = button1;
form1.CancelButton = button2;
If you want to perform some validation before the Form close, you then handle
Click[
^] event on the button.
And when the form is closed you can check on the result.
LoginForm login = new LoginForm();
DialogResult result = login.ShowDialog();
if (result == DialogResult.OK)
{
MessageBox.Show("User has loggedin");
}
else
{
MessageBox.Show("User failed validation");
}