Failed_Noob
Failed_Noob

Reputation: 1357

How to handle a form close event in vb.net

I have used the below code but its not showing the msgbox. What is wrong with this code ?

Private Sub frmSimple_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
       Dim result = MsgBox("Are you sure you want to Exit ?", vbYesNo)
       If result = DialogResult.Yes Then
        me.Close()
       End If
End Sub

Upvotes: 7

Views: 92856

Answers (7)

Josh Face
Josh Face

Reputation: 107

This code may not be 'efficient' but allows the user to save their work before closing, close the form if they press 'No' or return back to the form without closing if they press 'Cancel'.

        Dim dialog As DialogResult
        dialog = MessageBox.Show("Save before closing?", "Exit", MessageBoxButtons.YesNoCancel)
        If dialog = DialogResult.Yes Then
            'Put a save file dialog here or Button.PerformClick() if you already have a save button programmed
        ElseIf dialog = DialogResult.No Then
            Application.Exit()
        ElseIf dialog = DialogResult.Cancel Then
            e.Cancel = True
        End If

Upvotes: 0

CLAUDIO
CLAUDIO

Reputation: 31

If MessageBox.Show("¿Exit?", "Application, MessageBoxButtons.YesNo, _
                        MessageBoxIcon.Question) = DialogResult.No Then
            e.Cancel = True
        End If

Upvotes: 2

Filippo
Filippo

Reputation: 11

I think it is more clean and simply!

If MsgBox("Are you sure you want to Exit ?", vbYesNo) = vbNo Then e.Cancel = True

Upvotes: 1

Sivashankar
Sivashankar

Reputation: 21

 Dim result = MsgBox("Are you sure you want to Exit ?", vbYesNo)

       If result = vbYes Then
        me.Close()
       End If

Upvotes: 2

ProblemAnswerQue
ProblemAnswerQue

Reputation: 545

  Private Sub frmProgramma_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    If MessageBox.Show("Are you sur to close this application?", "Close", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
    Else
      e.Cancel = True
    End If
  End Sub

or that is how i use it everytime over and over...

Upvotes: 7

Jack
Jack

Reputation: 8941

Use FormClosing event. MSDN

Upvotes: 3

SLaks
SLaks

Reputation: 887215

This code runs after the form has been closed, when it's being disposed.
Depending on how you're showing the form, it might not get disposed at all.

You need to handle the FormClosing event and set e.Cancel to True if you want to cancel the close.

Upvotes: 16

Related Questions