65.9K
CodeProject is changing. Read more.
Home

Find out what's closing your application

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.17/5 (5 votes)

Oct 13, 2002

viewsIcon

106461

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