I am looking to prompt the user to save data when they close a form window in a winforms application. I can't figure out how to trigger the prompt to the user, should they click the red box at the top right corner of the form.
My application currently has a boolean flag, that is set to True on textchanged event. So I will only need to check for the boolean value in whatever event is trigger by the red box.
Any advice?
If you override the form's OnFormClosing method, you have the chance to notify the user that changes have been made, and the opportunity to cancel closing the form.
The event provides you with a FormClosingEventArgs instance which has a CloseReason property (which tells you why the form is closing) as well as a Cancel property, which you can set to True to stop the form from closing.
I implent this code for C# hope so it useful to you
You need the FormClosing Event
You need to handle the
FormClosing
event. This event is raised just before the form is about to be closed, whether because the user clicked the "X" button in the title bar or through any other means.Because the event is raised before the form is closed, it provides you with the opportunity to cancel the close event. You are passed an instance of the
FormClosingEventArgs
class in thee
parameter. By setting thee.Cancel
property to True, you can cancel a pending close event.For example: