In addition to Solution 1:
An alternative to handling
FormClosing
, you can override the virtual method
System.Windows.Forms.Form.FormClosing
:
https://msdn.microsoft.com/en-us/library/system.windows.forms.form.onformclosing%28v=vs.110%29.aspx.
The event arguments type is the same,
FormClosingEventArgs
, so you control the cancellation of processing the same way, via
FormClosingEventArgs.Cancel
:
FormClosingEventArgs Class (System.Windows.Forms)[
^].
Note the you should better check up
FormClosingEventArgs.CloseReason
; usually, you need to prevent closing only when it's closing by the user via the form's control, so you have to check is the reason is
CloseReason.UserClosing
:
FormClosingEventArgs.CloseReason Property (System.Windows.Forms),
CloseReason Enumeration (System.Windows.Forms).
Overriding
FormClosing
has certain benefits over the event handling. Here is why: overridden code is simpler and more maintainable, and the need to create a derived type is not a hassle, because Form types are usually derived in the application anyway.
—SA