This will work fine as long as the user clicks the Exit button to save, but a user does not necessarily end the program by selecting the exit button. What happens it they close the program using the X on the right, or some other way? The modifications below will ask the user if they want to save when they close the application, no matter how they close. The FormClosing event has a variable e that has a cancel property. If cancel is set to true, the program does not close. When the user tries to close the form, we will call AskToSave. If they select Cancel, then we set the global variable Canceled to true. When we return to the FormClosing event, we will set e.Cancel to Cancelled.
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) _ Handles Me.FormClosing Canceled = False AskToSave() If Canceled Then e.Cancel = True 'Program does NOT end! End Sub 'Form1_FormClosing
If Answer = MsgBoxResult.Cancel Then Canceled = True End If