This is commonly done in document-managed apps where a user can edit a document
and is then prompted to save the document prior to closing. If the user chooses
to cancel the save then the form does not close. In .NET this can be accomplished
by overriding the OnFormClosing method or by handling the FormClosing
method. This method/event allows you to cancel the event (such as if the user
cancels the save operation). For example, the following code will prompt the
user to save a document. If they cancel the save then the form is not closed.
protected override void OnFormClosing ( FormClosingEventArgs e )
{
base.OnFormClosing(e);
if (!e.Cancel && DocumentIsDirty)
{
switch(ShowSaveDialog())
{
case DialogResult.Yes : SaveDocument(); break;
case DialogResult.No : break;
case DialogResult.Cancel : e.Cancel = true; break;
};
};
}
Refer to the FAQ section for an issue with how form closing works. A final note, in v1.x you would use OnClosing
and Closing. This method/event has been deprecated in lieu
of the new v2 method/event.