in the code :

Code:

Private Sub Form1_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        MsgBox("form closed")
    End Sub 'Form1_Closing


replace msgbox("form closed") with the code to be run when the form closes.
do not put infinite while loops which will jam up the program