Search code examples
.netwinformsshutdownapplication-shutdown

Prompt user to save when closing app


I'm writing what boils down to a document editor. When the application is closing, I need to prompt the user to save changes. This is easy enough. My question is when is it appropriate to not prompt the user, and instead simply discard unsaved data and close.

In the FormClosing event, the CloseReason enum includes:

  • None
  • WindowsShutDown
  • MdiFormClosing
  • UserClosing
  • TaskManagerClosing
  • FormOwnerClosing
  • ApplicationExitCall

I figure that WindowsShutDown and TaskManagerClosing should not cause a "save changes?" prompt to appear, to prevent the app from hanging with that prompt showing.

Is this standard practice, or should I be doing something else here?

For clarity, here's the code:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    base.OnFormClosing(e);

    if (!(e.CloseReason == CloseReason.WindowsShutDown || e.CloseReason == CloseReason.TaskManagerClosing)
            && this.ChangesPending())
    {
        switch (MessageBox.Show(this, "Save changes?", "Save Changes", MessageBoxButtons.YesNoCancel))
        {
            case DialogResult.Yes:
                this.Save();
                break;
            case DialogResult.No:
                // Do nothing
                break;
            case DialogResult.Cancel:
                e.Cancel = true;
                break;
        }
    }
}

Solution

  • I think TaskManagerClosing should be the only reason that does not prompt, if any. Personally, I would want to be prompted in the event of WindowsShutDown. If I'm shutting down Windows with an unsaved document somewhere, it means I've forgotten about it.