Prompt user to save when closing app

后端 未结 5 985
耶瑟儿~
耶瑟儿~ 2021-01-13 09:12

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

5条回答
  •  逝去的感伤
    2021-01-13 09:58

    Really the CloseReason is a moot point, isn't it? The fact that your form is going away is what you're trying to catch.

    Now you need to know if your application has already handled the "save" event. If so, the form can go away. You've saved your document. But if not, you may want to prompt the user.

    If you can validate the data quickly (i.e. do a string compare or hash compare on the document compared to the data in the file) then you'll know if the user has saved the form data.

    Otherwise, if there are alot of fields, and checking each one is resource-prohibitive, then put a "isDirty" flag on your form. Let the Save() method set the isDirty to false, and every other field change sets it to true.

    Then, in formClosing, all you need is :

    protected override void OnFormClosing(FormClosingEventArgs e)
    {
        if (isDirty) 
        {
            DialogResult R = MessageBox.Show(this, "Save changes?", "Save Changes", 
                    MessageBoxButtons.YesNoCancel);
    
            if (R == DialogResult.Yes)
            {
                this.Save();
            } else if (R == DialogResult.Cancel)
            {
                e.Cancel = true;
            }
        }
    }
    

提交回复
热议问题