Search code examples
vb6

Form closing Event in VB6?


Just wanted to ask, Is there a form_closing event equivalent in VB6? (.bas). the reason I ask is that I wanted to prevent first closing the application if there's an open sub-window.

something like this.

Private Sub MainForm_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing

  If hasSubWindow Then
    MessageBox.Show("You currently have active sub-window(s)")
    e.Cancel = false
  End If

End Sub


Solution

  • There are three events: Form_QueryUnload(Cancel As Integer, UnloadMode As Integer), Form_Unload(Cancel As Integer) and Form_Terminate().

    Form_QueryUnload fires before the Form_Unload where setting Cancel to any value other than 0 cancels the unload and UnloadMode indicates the cause of the unload event.

    See https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445536(v=vs.60)?redirectedfrom=MSDN

    Form_Unload takes an integer that if set to any value other than 0, cancels the Unload.

    The Unload event procedure is where programmers usually put cleanup code. The Unload event fires after the QueryUnload event. The Unload event procedure takes a single parameter, the Cancel parameter. Unload's Cancel parameter works the same as QueryUnload's Cancel parameter.

    The Terminate event happens when the instance of the form has been completely unloaded and all the form's variables have been set to Nothing. The Terminate event happens only when you explicitly set the form to Nothing in your code during or after the Unload event procedure.

    Source: https://www.freetutes.com/learn-vb6-advanced/lesson6/p5.html

    In your case, you probably want to put code into Form_QueryUnload or Form_Unload that checks if there are any other open forms.

    Private Sub Form_Unload(Cancel As Integer)
        If hasSubWindow = True Then
             MsgBox "You currently have active sub-window(s)", vbInformation, "Confirm"
            Cancel = 1
        End if
    End Sub