I need to check whether the user really want to close the form.
But if I do this in Formclosing, the form will be closed anyway.
Printable View
I need to check whether the user really want to close the form.
But if I do this in Formclosing, the form will be closed anyway.
You can use e.Cancel to close or cancel closing the form.
vb.net Code:
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing If MsgBox("Are you sure you want to close?", MsgBoxStyle.YesNo, "Close?") = MsgBoxResult.Yes Then e.Cancel = False Else e.Cancel = True End If End Sub
This question has already been answered nicely by Link, though this sample code uses the preferred .Net framework System.Windows.Forms namespace version of the message box as opposed to the Microsoft.VisualBasic.Interaction namespace version:
Code:Private Sub Form1_FormClosing(ByVal sender As Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
Select Case MessageBox.Show("Are you sure you want to close?", "Confirm form closure", _
MessageBoxButtons.YesNo, MessageBoxIcon.Question)
Case Windows.Forms.DialogResult.Yes
e.Cancel = False
Case Else
e.Cancel = True
End Select
End Sub
To summarize it all on one line:Code:Private Sub Form1_FormClosing(...) Handles Me.FormClosing
e.Cancel = MessageBox.Show("Are you sure you want to close?", "Confirm form closure", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes
End Sub