I found that putting code in the WndProc method of the forms can be used to detect when the form is being closed. That way the form can do its dutties regardless of how the form is closed (close button, menu option, clicking the X, closing the app) or who closes the form (the app itself or windows.)
The benefit of this approach is that it does not depend on the caller form keeping track of it. The disadvantage is that is more complicated than it should be.
For the benefit of the lurkers, here is a preeliminary (read incomplete) version of the code:
Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)
Const WM_QUERYENDSESSION As Integer = &H11
Const WM_SYSCOMMAND As Integer = &H112
Const SC_CLOSE As Integer = &HF060&
Const WM_CLOSE As Integer = &H10
If m.Msg = WM_CLOSE Then
MessageBox.Show(Me.Text + " - WndProc close")
End If
If m.Msg = WM_SYSCOMMAND Then
If m.WParam.ToInt32 = SC_CLOSE Then
MessageBox.Show(Me.Text + " - WndProc syscmd close")
End If
End If
MyBase.WndProc(m)
End Sub
Hector Correa