Question

With this code:

private void PlatypusMainForm_FormClosing(object sender, FormClosingEventArgs e) {
    if ((UnsavedChanges()) && (!(UserWantsToMoveOnWithoutSaving(CONFIRM_CLOSE_UNSAVED_CHANGES_LOST, "Close Without Saving?")))) {
        e.Cancel = true;
        return;
    }
    if (oracleConnectionMainForm.State == ConnectionState.Open) {
        oracleConnectionMainForm.Close();
        oracleConnectionMainForm.Dispose();
    }
}

...if e.Cancel = true is commented out, the form closes anyway.

...if return is commented out, the rest of the code (Close and Dispose) runs (so, if I then try to save changes, I get the err msg that the connection is not open).

So, I have to do both (cancel and return) to get the code to work as I think it should with either one.

Is this normal/as expected?

Was it helpful?

Solution

Yes, that's as expected. The e.Cancel tells the framework that you've handled the event, and you don't want the automatic behavior. Without it, after your method returns, the framework will continue to handle the event, and close the window.

The return aborts the execution of this current method, so the stuff at the end doesn't execute.

OTHER TIPS

Cancel is defaulted to false, so if you comment it out it never gets set to true. Take return out and it doesn't return until after the rest of the code executes, or in your case errors.

if (SomeCondition)
{
  e.Cancel = true;
}
else
{
  // Do Something
}

would be clearer, and be slightly less complex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top