【问题标题】:How to save data when closing event happen in WinForms?WinForms中发生关闭事件时如何保存数据?
【发布时间】:2014-07-21 09:18:30
【问题描述】:

我想要一个消息框来询问有关表单关闭事件的未保存数据。

如果用户选择是,则将数据保存在文本文件中并退出应用程序。

如果用户在不保存的情况下选择不退出应用程序。

我尝试了下面的代码。但是它并没有关闭应用程序并让消息框一次又一次地出现。

  public void SaveMyFile()
    {
        //// Create a SaveFileDialog to request a path and file name to save to.
        SaveFileDialog saveFile1 = new SaveFileDialog();

        //// Initialize the SaveFileDialog to specify the RTF extension for the file.
        saveFile1.DefaultExt = "*.txt";
        saveFile1.Filter = "Info Changed Data (*.txt)|*.txt";

        //// Determine if the user selected a file name from the saveFileDialog. 
        if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
           saveFile1.FileName.Length > 0)
        {
            //// Save the contents of the RichTextBox into the file.
            richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);
        }
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            SaveMyFile();
            this.Close();
        }
        else if (dialogResult == DialogResult.No)
        {
            this.Close(); 
        }
    }

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    删除该行

    this.Close();
    

    没有必要。应该是这样的:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            SaveMyFile();
        }
    }
    

    或者像这样:

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show("Do You Want To Save Your Data", "CodeJuggler", MessageBoxButtons.YesNoCancel);
            if (dialogResult == DialogResult.Yes) SaveMyFile();
            else if (dialogResult == DialogResult.Cancel) e.Cancel = true;
        }
    

    【讨论】:

    • 在选择是并保存文件时,它会再次弹出消息询问相同的问题。
    • @swagger 即使您通过删除 this.Close() 语句修改了代码?我现在已经尝试过了,对我来说它工作得很好。
    【解决方案2】:

    “...一次又一次”没有循环通常暗示程序中有一些回避。

    在您的情况下,您在Closing 事件处理程序中调用Form.Close(),然后引发Closing 事件,您在其中调用Form.Close() 并且......我想你明白了。

    只需删除对Close() 的调用,您就不需要它们了。如果引发了Closing,那么您的表单将被关闭除非您将FormClosingEventArgs 参数中的Cancel 属性设置为true

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-06-22
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多