在winforms应用程序中的窗口关闭事件

7

我想在WinForms应用程序中的表单窗口关闭时提示用户保存数据。我无法弄清如何触发提示,当他们点击窗体右上角的红色框时。

我的应用程序目前有一个布尔标志,在文本更改事件上设置为True。因此,我只需要在由红框触发的任何事件中检查布尔值即可。

有什么建议吗?

4个回答

14
你需要处理 FormClosing 事件 无论用户是通过单击标题栏上的“X”按钮还是其他任何方式,该事件在窗体即将关闭时触发。
因为该事件在窗体关闭之前被触发,所以它提供了取消关闭事件的机会。你可以在e参数中获得 FormClosingEventArgs 类的实例。通过将 e.Cancel 属性 设置为 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 参数。 - Hans Passant

5
如果你覆盖了表单的OnFormClosing方法,你有机会通知用户已经进行了更改,并有机会取消关闭表单。
该事件为您提供了一个FormClosingEventArgs实例,其中包含一个CloseReason属性(告诉您为什么表单正在关闭),以及一个Cancel属性,您可以将其设置为True以防止表单关闭。

5

我编写了这段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;
        }

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接