Files in Visual Basic

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.

  1. Add another global variable: Dim Canceled as Boolean
  2. Write the code for formClosing as shown below:
  3. Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) _
      Handles Me.FormClosing
        Canceled = False
        If Canceled Then e.Cancel = True 'Program does NOT end!
    End Sub 'Form1_FormClosing
  4. Modify AskToSave by adding the code shown below:
  5. If Answer = MsgBoxResult.Cancel Then
       Canceled = True
    End If
View the complete code.

NEXT: Reformatting Files