Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Find out what's closing your application

0.00/5 (No votes)
15 Oct 2002 1  
Code in VB.NET to find out what's closing your application.

Introduction

You can use this code to see why your application is closing (closed by user, by Windows, by code?). It can be very handy if you are using a NotifyIcon in your app. You can figure out if the user is closing your app or not, if so, then you can just minimize it to tray.

For those who have used Visual Basic before, you know that there was a QueryUnload method for your Forms and that you could find out the reason for the form's closing by examining the UnloadMode variable.

This code snippet shows you how to do this in .NET. The sample code is in VB.NET. The code is from GotDotNet message boards, written by "YeahIGotDotNet".

Private Sub Form1_Closing(ByVal sender As Object, _
  ByVal e As System.ComponentModel.CancelEventArgs) _
  Handles MyBase.Closing
    Dim O As System.Diagnostics.StackTrace = _
           New System.Diagnostics.StackTrace(True)
    Dim F As System.Diagnostics.StackFrame

    F = O.GetFrame(7)

    Select Case F.GetMethod.Name.ToString
        Case "SendMessage"
            MsgBox("Closing because of call in code.")
        Case "CallWindowProc"
            MsgBox("Closing because of system menu click.")
        Case "DispatchMessageW"
            MsgBox("Closing because of Task Manager.")
        Case Else
            MsgBox("Don't Know why I'm closing!!??")
    End Select
End Sub

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here