I tried to prevent a form from closing by handling the FormClosing.
if(e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
SomeFunction();
}
However, when it gets in the SomeFunction(), a stackoverflow exception is thrown.
What could be the reason for this? Thanks.
EDIT:
Oops my bad for not debugging. The SomeFunction() has some field validations in it and when the fields are valid, I call the form’s Close() function. And since I have the handling on the FormClosing(), it will go through again in the SomeFunction(). I didn’t know that calling the Close() function is also under the CloseReason.UserClosing. Thanks for your answers.
A common cause for a stack overflow is an infinite recursion.
You should check that
SomeFunction()does not causeSomeFunction()to be called again (possible by triggering the event you are handling.You can check the call stack in the debugger to see if this is the case (as per the comments above).