Improve application close

Developer
Mar 24, 2009 at 1:41 AM
Currently, users can choose whether or not to save the file when they close the application.  I think it would be better if you could also cancel the close for those occasions when you accidently click close.  This is how I altered the OnClosing method in MainWindow.xaml.cs to do this:

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            // Make sure the file is saved before the app is closed.  Allows user to cancel close request or to close without saving.
           
            if (!family.IsDirty)
            return;

            MessageBoxResult result = MessageBox.Show(Properties.Resources.NotSavedMessage,
                Properties.Resources.NotSaved, MessageBoxButton.YesNoCancel, MessageBoxImage.Warning);

            if (result == MessageBoxResult.Yes)
            {
             // Prompt to save if the file has not been saved before, otherwise just save to the existing file.
                if (string.IsNullOrEmpty(familyCollection.FullyQualifiedFilename))
                {
                    CommonDialog dialog = new CommonDialog();
                    dialog.InitialDirectory = People.ApplicationFolderPath;
                    dialog.Filter.Add(new FilterEntry(Properties.Resources.FamilyFiles, Properties.Resources.FamilyExtension));
                    dialog.Filter.Add(new FilterEntry(Properties.Resources.AllFiles, Properties.Resources.AllExtension));
                    dialog.Title = Properties.Resources.SaveAs;
                    dialog.DefaultExtension = Properties.Resources.DefaultFamilyExtension;
                    dialog.ShowSave();

                    if (!string.IsNullOrEmpty(dialog.FileName))
                    {
                        familyCollection.Save(dialog.FileName);
                        // Remove the file from its current position and add it back to the top/most recent position.
                        App.RecentFiles.Remove(familyCollection.FullyQualifiedFilename);
                        App.RecentFiles.Insert(0, familyCollection.FullyQualifiedFilename);
                    }
                }
                else
                {
                    familyCollection.Save();

                    // Remove the file from its current position and add it back to the top/most recent position.
                    App.RecentFiles.Remove(familyCollection.FullyQualifiedFilename);
                    App.RecentFiles.Insert(0, familyCollection.FullyQualifiedFilename);
                }
                base.OnClosing(e);        
            }
           
           if (result == MessageBoxResult.No)
           {
           base.OnClosing(e);
           }
           if (result == MessageBoxResult.Cancel)
           {
           e.Cancel = true;
           }
        }