Search code examples
vb.netformseventssenderformclosing

vb.net: Distinguish between me.close() and x-button


how is it possible to distinguish between the event, that the user explicitly pressed to x-button (or pressed ALT F4) to close a form and all other methodes of closing the form programatically (me.close(), etc). I already figured out, that this could be done using sender objects but I don't really get it. Could somebody explain it for me with an example? Thank you all very much in advance.


Solution

  • The class FormClosingEventArgs event args has an enumeration to tell what the reason the form is closing.

    https://msdn.microsoft.com/en-us/library/system.windows.forms.closereason(v=vs.110).aspx

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As FormClosingEventArgs) Handles Me.Closing
    
        If Not appClosing AndAlso e.CloseReason = System.Windows.Forms.CloseReason.UserClosing Then
    
        ' DO WHATEVER CODE YOU WANT IN HERE
        ' LIKE SETTING E.CANCEL TO TRUE
    
        End If
    
    End Sub
    
    ' You can also set a close appClosing local variable at the class level as a boolean, whenever you call closing in code, assign the variable.
    appClosing = True
    Me.Close();