Form, CancelButton, Escape, prevent Form close

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();

}

}
 
T

Thomas Schupp

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
 
T

Thomas Schupp

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top