Right now if a user closes the form (either by clicking 'X' or chosing exit from a menu option) and changes are detected in the form, a messagebox will display asking the user if they would like to save any changes. The user has the option of clicking "yes, no or cancel." The problem I am having is with the cancel button. Every variation I've tried is still causing the form to close, even if cancelled is clicked. How can clicking cancel, essentially do nothing and go back to the form?

Private Sub PFC_XPRESS_FormClosing(sender As System.Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        Dim Result As DialogResult

If saved = False Then

                Result = MessageBox.Show("Would you like to save changes?", "Confirm Exit", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

ElseIf Result = Windows.Forms.DialogResult.No Then
                Application.Exit()

Elseif Result = Windows.Forms.DialogResult.Cancel Then
                'Do Nothing

ElseIf Result = Windows.Forms.DialogResult.Yes Then

                Call Savefiledialog()

End If

Dani AI

Generated

A quick, focused explanation: the FormClosing handler must set e.Cancel = True to keep the form open — that's what pointed out. The original code from both failed to set e.Cancel and mixed the message-box logic into the wrong branches so Result was not reliably tested. A cleaner, more robust pattern is to prompt only for user-initiated closes, treat a Cancel result as a hard cancel, and only allow the form to close after a successful save (or when the user explicitly chooses No).

Private Sub MainForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    ' Prompt only when the user initiated the close and there are unsaved changes
    If e.CloseReason = CloseReason.UserClosing AndAlso Not saved Then
        Dim r As DialogResult = MessageBox.Show("Save changes before exit?", "Confirm Exit", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)

        Select Case r
            Case DialogResult.Cancel
                e.Cancel = True                              ' stop closing
            Case DialogResult.Yes
                If Not SaveData() Then e.Cancel = True       ' keep open if save fails
            Case DialogResult.No
                ' allow close
        End Select
    End If
End Sub

Practical cautions and tips:

  • Make SaveData() return True/False and only clear the saved flag after a successful save.
  • Avoid calling Application.Exit() from inside FormClosing — that can re-enter the shutdown sequence.
  • Respect e.CloseReason (Windows shutdown/task manager closes should be handled differently).
  • If save is asynchronous, await it or cancel the close until it finishes; set e.Cancel = True if it fails.
  • Remember FormClosed is too late to cancel; canceling must happen in FormClosing.

Recommended Answers

All 3 Replies

Try this:

    Private Sub frmMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

        'If there are unsaved changes to the active library, ask user what to do.

        Dim msgTitle As String = "You have unsaved changes"
        Dim msgPrompt As String = "Do you want to save your changes before closing?" & vbCrLf _
                                & vbCrLf _
                                & "    Yes    - save changes and exit" & vbCrLf _
                                & "    No     - discard changes and exit" & vbCrLf _
                                & "    Cancel - resume application"

        If Unsaved() Then

            Select Case MsgBox(msgPrompt, vbYesNoCancel, msgTitle)

                Case vbYes      'save changes and exit                                  
                    SaveBookList(Library)
                    MsgBox("Library has been saved in " & Library)

                Case vbCancel   'return to application                                  
                    e.Cancel = True

                Case vbNo       'discard changes and exit                               

            End Select

        End If

     End Sub

I used this in a BookLib app I wrote a while back. The Sub, Unsaved, returns true if there are changes that haven't been saved to disk.

It worked! Can't believe I forgot that part. Thanks Jim!

In case you missed it I revised the code a tad to give three options. It might have posted after you replied.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.