Form, CancelButton, Escape, prevent Form close

  • Thread starter Thread starter AP
  • Start date Start date
A

AP

Hi,

I have a form that has a Close button. I set this close button to be the
CancelButton for my form. When the close button is pressed, if there have
been any changes made to the form, I popup a MessageBox asking the user if
they wish to save their changes, using the YesNoCancel message buttons. If
the user hits cancel obviously I do not want to close the form. If the user
hits close I call Close on the form. This works fine for when the user
clicks the close button, but when they hit escape the form closes whether
they hit cancel and I call Close or not. How can I get around this?
I've pasted code sample below.

Thanks,

Adam

private void bClose_Click(object sender, System.EventArgs e) {

FormClose();

}

protected virtual void FormClose() {

bool close = true;

if (myDataPanel.HasChanges()) {

DialogResult dr =

UIHelperController.Instance.ShowQuestionMessageBox(this,"Changes
Made","Changes have been made to this panel. Would you like to save these
changes before closing?",MessageBoxButtons.YesNoCancel);

switch (dr) {

case DialogResult.Yes:

close = myDataPanel.Write();

break;

case DialogResult.No:

close = true;

break;

case DialogResult.Cancel:

close = false;

break;

}

}

if (close) {

Close();

}

}
 
Try the "Closing"-Event of the form. It has "ByVal e As
System.ComponentModel.CancelEventArgs". With "e.Cancel" you can avoid
closing the form.

Thomas
 
Right:
e.Cancel = True

Try the "Closing"-Event of the form. It has "ByVal e As
System.ComponentModel.CancelEventArgs". With "e.Cancel" you can avoid
closing the form.

Thomas
 
Back
Top