Sometimes you may want to close your forms in different ways (or not allow them to close, etc) depending on the reason that they are closing.

You can find this out by using the _QueryUnload event of the form, and simply checking the value of the UnloadMode parameter that is passed to it, which will be one of the following values:
  • vbFormControlMenu - The user chose the Close command from the Control menu on the form. (pressed the "X" button, or the form icon then "close")
  • vbFormCode - The Unload statement is invoked from code. (eg: "Unload Form1")
  • vbFormMDIForm - An MDI child form is closing because the MDI form is closing.
  • vbFormOwner - A form is closing because its owner is closing.
  • vbAppWindows - The current Microsoft Windows operating environment session is ending. (the user is logging out of Windows, or shutting down the computer)
  • vbAppTaskManager - The Microsoft Windows Task Manager is closing the application.
(Note that this list is copied from the help for QueryUnload)


As an example, if you don't want the form to close when the user presses the "X" button, you could use code like this:
Code:
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)

  If UnloadMode = vbFormControlMenu Then  'check if the X was pressed
    Cancel = True    'cancel the unloading
    Exit Sub
  End If

  '...

End Sub