Window close events in a winforms application

可紊 提交于 2019-11-28 01:19:09

You need to handle the FormClosing event. This event is raised just before the form is about to be closed, whether because the user clicked the "X" button in the title bar or through any other means.

Because the event is raised before the form is closed, it provides you with the opportunity to cancel the close event. You are passed an instance of the FormClosingEventArgs class in the e parameter. By setting the e.Cancel property to True, you can cancel a pending close event.

For example:

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

If you override the form's OnFormClosing method, you have the chance to notify the user that changes have been made, and the opportunity to cancel closing the form.

The event provides you with a FormClosingEventArgs instance which has a CloseReason property (which tells you why the form is closing) as well as a Cancel property, which you can set to True to stop the form from closing.

I implent this code for C# hope so it useful to you

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;
        }

You need the FormClosing Event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!