How does the e.Cancel event work in the FormClosing event on a WinForm? I know you set it to True
to cancel the closing, but at what point does the form process this? Is there a secondary action taken by the property?
How could I implement a similar action in a custom control? (C# or VB)
Note: I've looked for about 30 minutes now and couldn't find any answers in Google or the SO search, so if it's a duplicate, my bad.
I think the original poster might be wondering what happens when some subscribers set
Cancel = false
and some subscribers setCancel = true
. If this is the case, then the question "when does the form process this" takes on more importance.At first I wondered whether the setter was implemented to OR or AND each value. Using Reflector to inspect the setter for
CancelEventArgs.Cancel
shows it simply sets a private field:So I figured peeking into 'Form.OnClosing(CancelEventArgs args)' would show when the value is checked, like the previous answers, but that is not what Reflector shows:
So I enabled source debugging and found getting the
EVENT_CLOSING
delegate from theEvents
collection drops deep down into the windowing API such thathandler
in the first line ofOnClosing
isnull
when the form setsCancel = true
, meaning the managed code never really tests whetherCancelEventArgs.Cancel == true
. If you want the ugly guts of what happens inside the EventHandlerList, you get this:While debugging,
parent.CanRaiseEventsInternal
is false if the closing was cancelled.So ... the actual implementation of canceling the closing of a form is more complicated than the previous answers, but their suggestions for how to cancel your own events correctly show how to do it in managed code. Call the CancelEventHandler and then test the value of
CancelEventArgs.Cancel
after all the subscribers have had a chance to set the value totrue
. This still does not answer what happens if some subscribers setCancel = false
and some setCancel = true
. Does anyone know? Would something like the following be required?