【问题标题】:Window close events in a winforms applicationwinforms 应用程序中的窗口关闭事件
【发布时间】:2011-06-18 13:55:03
【问题描述】:

我希望在用户关闭 winforms 应用程序中的表单窗口时提示他们保存数据。如果他们单击表单右上角的红色框,我无法弄清楚如何向用户触发提示。

我的应用程序当前有一个布尔标志,在 textchanged 事件上设置为 True。所以我只需要检查红色框触发的任何事件中的布尔值。

有什么建议吗?

【问题讨论】:

    标签: .net vb.net winforms formclosing


    【解决方案1】:

    您需要处理FormClosing event此事件在表单即将关闭之前引发,无论是因为用户单击标题栏中的“X”按钮还是通过任何其他方式。

    因为在表单关闭之前引发了事件,它为您提供了取消关闭事件的机会。您在e 参数中传递了FormClosingEventArgs 类的实例。通过将e.Cancel property 设置为True,您可以取消挂起的关闭事件。

    例如:

    Private Sub Form_Closing(ByVal sender As Object, ByVal e As FormClosingEventArgs)
        If Not isDataSaved Then
            ' The user has unsaved data, so prompt to save
            Dim retVal As DialogResult
            retVal = MessageBox.Show("Save Changes?", YesNoCancel)
            If retVal = DialogResult.Yes Then
                ' They chose to save, so save the changes
                ' ...
            ElseIf retVal = DialogResult.Cancel Then
                ' They chose to cancel, so cancel the form closing
                e.Cancel = True
            End If
            ' (Otherwise, we just fall through and let the form continue closing)
        End If
    End Sub
    

    【讨论】:

    • 替代 OnFormClosing。注意e.CloseReason。
    【解决方案2】:

    如果您覆盖表单的 OnFormClosing 方法,您有机会通知用户已进行更改,并有机会取消关闭表单。

    该事件为您提供了一个 FormClosingEventArgs 实例,该实例具有一个 CloseReason 属性(告诉您表单关闭的原因)以及一个 Cancel 属性,您可以将其设置为 True 以阻止表单关闭。

    【讨论】:

      【解决方案3】:

      我为 C# 实现了这段代码,希望对你有用

      protected override void OnFormClosing(FormClosingEventArgs e)
                  {            
                      base.OnFormClosing(e);
                      if (PreClosingConfirmation() == System.Windows.Forms.DialogResult.Yes)
                      {
                          Dispose(true);
                          Application.Exit();
                      }
                      else
                      {
                          e.Cancel = true;
                      }
                  }
      
              private DialogResult PreClosingConfirmation()
              {
                  DialogResult res = System.Windows.Forms.MessageBox.Show(" Do you want to quit?          ", "Quit...", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                  return res;
              }
      

      【讨论】:

        【解决方案4】:

        您需要FormClosing 事件

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多