-1

I couldn't find any working answers for this, so I finally am asking it here. I have been working on a Calculator for a while in Visual Studio 2013. In that Calculator program, I have a Quit button. I want it to be so when a user clicks on "Quit" it has a popup that asks if they are sure, and then I want "OK" to close the program and "Cancel" to bring them back. I have the following code-

Private Sub Button18_Click(ByVal Sender As System.Object, ByVal e As System.EventArgs) Handles Button18.Click
    MsgBox("Are you sure you would like to Quit?", 1 + 16, "Quit")
End Sub

I have no clue how to make this work, so please answer, if you can help!

Mark Hall
  • 53,938
  • 9
  • 94
  • 111
  • Look into the [FormClosing Event](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.closing(v=vs.110).aspx) – Mark Hall Nov 14 '14 at 20:46
  • See [MessageBox Class](http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=vs.110).aspx). It returns a value. – LarsTech Nov 14 '14 at 20:49

2 Answers2

2

You should have a FormClosing handler, to account for different ways your form can be closed:

Private Sub Form1_FormClosing(sender As Object,
                                e As FormClosingEventArgs) Handles Me.FormClosing
  If e.CloseReason <> CloseReason.UserClosing Then Return

  Dim res As DialogResult = MessageBox.Show(
    "Are you sure?", "Confirmation", MessageBoxButtons.OKCancel)

  Select Case res
    Case DialogResult.OK
      'do nothing, we are already closing
    Case DialogResult.Cancel
      e.Cancel = True
    Case Else
      'should never get here
      Throw New NotImplementedException
  End Select
End Sub

Notice a condition on CloseReason, this is to prevent an annoying popup when the form is being closed externally, i.e. by a task manager. We only want the popup when it's user closing the form.

Next you need to save a DialogResult, returned by MessageBox.Show.

Since we are inside the FormClosing event handler, no action means a form will be closed. If you want to Cancel form closing, you need to set e.Cancel = True. See FormClosingEventArgs class on MSDN.

Case Else is there if you ever decide to change which buttons are available on the popup, and forget to update your Select Case accordingly.

Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
0

The following code answers your question, but follow Neolisk's answer to make a more robust app.

Private Sub Button18_Click(sender As Object, e As EventArgs) Handles Button18.Click
    Dim result As MsgBoxResult
    result = MsgBox("Are you sure you would like to Quit?", 1 + 16, "Quit")
    If (result = MsgBoxResult.Ok) Then
        Application.Exit()
    End If
End Sub
Community
  • 1
  • 1
mr_plum
  • 2,448
  • 1
  • 18
  • 31