Form::Close method, FormClosing event, and CloseReason event argument. Set custom CloseReason?

StackOverflow https://stackoverflow.com/questions/19705538

  •  02-07-2022
  •  | 
  •  

Question

This is a similar question to this one but I found the answer there didn't work when transposed to C++. The FormClosing event is always triggered by whatever method is used to close the form, so the value of _programmaticClose is always false on exit. Also, calling the base function OnFormCLosing resulted in an infinite loop!

I need to differentiate between the Apply button, Cancel button, 'X', Alt+F4, etc.

Was it helpful?

Solution

The property

FormClosingEventArgs.CloseReason

is read-only, so you can't manually change it after the Closing event is fired.

What you would need to do is define your own CloseReason enumeration.

enum CloseReason
{
    Apply, Cancel, X, AltF4 // etc...
}

And add two variables in your form:

private:
    bool forceClose = false;
    CloseReason closeReason;

Then in the FormClosing method, write this code (here I assume the event fires a method called Form1_FormClosing):

void Form1_FormClosing(Object sender, FormClosingEventArgs e)
{
    if (!forceClose)
        e->Cancel = true;
}

So by default, the form won't actually close when the user tries to close it.

Now for every "alternative" method you have of closing the form, you need to write another event handler that tells the form how it is being closed, as well as actually closing it if appropriate. For instance, if you have a button named ApplyButton that you want to close your form:

void ApplyButton_Click(Object sender, EventArgs e)
{
    closeReason = CloseReason::Apply;
    forceClose = true;
    this->Close();
}

And just repeat that format for other closing methods. When your user closes the form using "X", only the FormClosing method will be called, so you need to write extra code in that method if you want anything special to happen.

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