Search code examples
vb.netmessageboxformclosing

on form closing event i am puzzeled


I want it so when the "x" button is clicked a message box will appear saying "Are you sure you want to exit?" then if "yes" it closes and if "NO" it stays open. so my code is:

Dim a As Integer
a = MessageBox.Show("Are you sure you want to exit?", _
                    "Vice Versa 1.0", _
                    MessageBoxButtons.YesNo, _
                    MessageBoxIcon.Information)
If a = vbYes Then
  Me.Close()
Else
  Exit Sub
End If

This should work, no? When i debug my project clicking "no" still exits my program. Is this just because it's in debug mode or am i missing something here?

(EDIT:) Also no warnings or errors.

Is there a way i can make my game pause when the message box shows? I only have it working to if the users presses "p" on keyboard. But also want game paused when message box shows, without pressing "p"


Solution

  • You also have to set the Cancel property to cancel the close. On the line before Exit Sub, add:

    e.Cancel = True
    

    and you don't have to do the Me.Close again. A better way to write your If block would simply be to have:

    a = MessageBox.Show(....)
    If a = DialogResult.No Then
        e.Cancel = True
    End If