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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…