Visual Basic Reference

QueryUnload Event Example

This example uses an MDIForm object containing two MDI child forms. When you choose the Close command from the Control menu to close a form, a different message is displayed than if you choose the Exit command from the File menu. To try this example, create an MDIForm, and then use the Menu Editor to create a File menu containing an Exit command named FileExit. Make sure that this menu item is enabled. On Form1, set the MDIChild property to True. Paste the code into the Declarations sections of the respective forms, and then press F5 to run the program.

  ' Paste into Declarations section of MDIForm1.
Private Sub MDIForm_Load ()
   Dim NewForm As New Form1   ' New instance of Form1.
   NewForm.Caption = "Form2"   ' Set caption and show.
End Sub

Private Sub FileExit_Click ()
   Unload MDIForm1   ' Exit the application.
End Sub

Private Sub MDIForm_QueryUnload (Cancel As Integer, UnloadMode As Integer)
   Dim Msg   ' Declare variable.
   ' Set the message text.
   Msg = "Do you really want to exit the application?"
   ' If user clicks the No button, stop QueryUnload.
   If MsgBox(Msg, vbQuestion + vbYesNo, Me.Caption) = vbNo Then Cancel = True
End Sub

' Paste into Declarations section of Form1.
Private Sub Form_QueryUnload (Cancel As Integer, UnloadMode As Integer)
   Dim Msg   ' Declare variable.
   If UnloadMode > 0 Then
      ' If exiting the application.
      Msg = "Do you really want to exit the application?"
   Else
      ' If just closing the form.
      Msg = "Do you really want to close the form?"
   End If
   ' If user clicks the No button, stop QueryUnload.
   If MsgBox(Msg, vbQuestion + vbYesNo, Me.Caption) = vbNo Then Cancel = True 
End Sub