See Also Example
Applies To
Form, MDI Form
Description
Occurs when a form is about to be removed from the screen. When that form is reloaded, the contents of all its controls are reinitialized. This event is triggered by user action (closing the form using the Control-menu box), or by an Unload statement.
Syntax
Sub { Form|MDIForm}_Unload (Cancel As Integer)
Remarks
Setting Cancel to any nonzero value prevents the form from being removed, but does not stop other events such as exiting from Windows. Use the QueryUnload event to stop exiting from Windows.
Use an Unload event procedure to verify that the unloading of the form should proceed or to specify actions that should take place when the form is unloaded. You can also include any form-level validation code you might need for closing the form or saving the data in it to a file.
The QueryUnload
The Unload event can be caused by using the Unload
Help:
Load Event
Load Statement
QueryUnload Event
Unload Statement
Programmer's Guide:
Chapter 18, "Using the File-System Controls"
The example demonstrates a simple procedure to close a form while querying the user with various message boxes. In an actual application, you could add calls to general-purpose Sub procedures that emulate the processing of the Exit, Save, and Save As commands on Visual Basic's File menu. To try this example, paste the code into the Declarations section of a form. Then press F5. Once the form is displayed, press Alt + F4 to close the form.
Sub Form_Unload (Cancel As Integer)
Dim Msg, Response ' Declare variables.
Msg = "Save Data before closing?"
Response = MsgBox(Msg, 3 + 32, "Save Dialog")
Select Case Response
Case 2 ' Do not allow close.
Cancel = -1
Msg = "Command has been cancelled."
Case 6
' Enter code to save data here.
Msg = "Data saved."'
Case 7
Msg = "Data not saved."
End Select
MsgBox Msg, 0, "Confirm" ' Display message.
End Sub