Reputation: 395
I want to close the main form from a "Sub"; as I am using the sub from the "Exit" of the Menu too; I wrote the code below, but I am having problem when user click "Cancel" in the YesNoCancel Dialog; My code is below:
If MekdamFirstLetters = "*" Then
Dim result = MessageBox.Show("The File: " & _
vbCrLf & _
" (" & File & ".txt) has been changed," & _
vbCrLf & _
" do you want to save it? ", _
"Mekdam Message 701", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If result = DialogResult.Cancel Then
'***********************
' THE ISSUE IS HERE;
'Me.Cancel = True
'***********************
ElseIf result = DialogResult.No Then
Application.Exit()
ElseIf result = DialogResult.Yes Then
SaveFileDialog()
Application.Exit()
End If
End If
Upvotes: 2
Views: 78
Reputation: 54562
As I mentioned in my Comment your best bet would to put your code into the FormClosing
EventHandler, this will give you the opportunity to cancel the close.
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If MekdamFirstLetters = "*" Then
Dim result = MessageBox.Show("The File: " & _
vbCrLf & _
" (" &
File & ".txt) has been changed," & _
vbCrLf & _
" do you want to save it? ", _
"Mekdam Message 701", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
If result = DialogResult.Cancel Then
e.Cancel = True 'This will stop the form from closing
ElseIf result = DialogResult.No Then
'Application.Exit() 'no need to explicitly exit, you are already doing it this will lead to a loop
ElseIf result = DialogResult.Yes Then
SaveFileDialog()
'Application.Exit() 'Same here
End If
End If
End Sub
Upvotes: 3