Get application Shutdown event when using a context class

Hi!

I start my applciation using  Application.Run(New MyContext)

When the applcaition is shutting down I need to do some stuff, so how do I catch that shutting down event when not having any form that is closing

Public Class MyContext
    Inherits ApplicationContext

    Public Sub New()
        ' do some stuff
    End Sub
End Class
LVL 1
AWestEngAsked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
In this example, if "/close" is passed in then the application will close.  The ShutDown() event fires a Msgbox to show you that you can put cleanup code in there:
    Partial Friend Class MyApplication
 
        Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
            For Each param As String In e.CommandLine
                Debug.Print(param)
            Next
        End Sub
 
        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            If e.CommandLine.Count = 1 AndAlso e.CommandLine(0).ToUpper = "/CLOSE" Then
                Application.MainForm.Close()
            End If
        End Sub
 
        Private Sub MyApplication_Shutdown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shutdown
            MessageBox.Show("Shutdown()")
        End Sub
 
    End Class

Open in new window

0
 
nsangaCommented:
have you tried defining a handler for ApplicationExit in MyContext constructor as below


AddHandler Application.ApplicationExit, AddressOf OnApplicationExit
0
 
SameerJagdaleCommented:
you need to handle formclosing event of MyContext (assuming it is a form). in closing event, check for e.closereason..
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
AWestEngAuthor Commented:
MyContext is no form its a Context class
0
 
AWestEngAuthor Commented:
does Application.ApplicationExit cast an event for all types of shutdowns? even if I terminate the application  process from outide
0
 
AWestEngAuthor Commented:
it dosen't  work when killing the process outside the application, I need a common application shutdown method that will take all types of shutdowns
0
 
nsangaCommented:
I haven't checked it........

But what I believe is if you try to terminate the application process from outide ( like using Task Manager ), I don't think application has a control to handle its events.........for such cases, I think you may need to have advanced OS level programming.......
0
 
AWestEngAuthor Commented:
the SessionEnding doesn't work either
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
When you use "End Process" in Task Manager your app doesn't get the chance to clean up as it is killed with the TerminateProcess() API:
http://msdn.microsoft.com/en-us/library/ms686714(VS.85).aspx

You can't trap this...
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Since your app doesn't have an interface...how exactly would one close your app in a "controlled" fashion anyways?...  =\

0
 
AWestEngAuthor Commented:
I don't use the End Process" in Task Manager I use the kill command in the process type
 dim test as Process
------
test .Start
 test.Kill
0
 
AWestEngAuthor Commented:
but that my be the same, I don't know. :)
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Yes...I'm pretty sure Kill uses TerminateProcess() internally.  If you use CloseMainWindow it sends WM_CLOSE to the main window...but this doesn't apply to your situation.  =\

0
 
AWestEngAuthor Commented:
oki. then I have to come up with another way to start up and kill the app. any tips there.
can I use something else then Process to start an application that will add a better way to kill the app,?
0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
With regard to cleanup...if you have no user interface then you are SOL...if the USER initiates the shutdown they have no option except to use the TaskManagers "End Process", Process.Kill, or some other functionally equivalent method.  When that route is taken your app will just die...it will blink out without even knowing it is closing.

If you want the ability to PROGRAMATICALLY shutdown your app then we can open up some options.  I think you need to re-engineer your app so that it uses the default Application Framework.  Use an Invisible Form as the "Startup Form" by setting the Opacity to 0 (zero) and the ShowInTaskBar property to False.

This gives you several advantages:
(1) You get true built-in single instancing with an Event that fires for you when another instance is opened.
(2) You can pass in a command line parameter to tell the app to shutdown.  (These parameters are made available to the already running instance.)
(3) You can properly determine when the system is being logged of/shutdown and do your cleanup.
(4) You can easily add an Icon down in the System Tray so the user can access a ContextMenu to interact with your app while it is "hidden".

I'm fairly certain the original code can be modified to achieve this. =)
http://www.experts-exchange.com/Programming/Languages/.NET/.NET/Q_23724631.html

Thoughts?...
0
 
AWestEngAuthor Commented:
oki. I will paste the code I use to day, 2 sec
0
 
AWestEngAuthor Commented:
Here is what I use today and this is what I need to do if I change the code, as you can see I use DevExpress and I need to run some stuff in the startup to get that working correct.
  DevExpress.UserSkins.OfficeSkins.Register( )  DevExpress.Skins.SkinManager.EnableFormSkins()
 any tips how to redesign this? :)
I really appreciated that you are helping  me Idle_Mind thx m8 :)

Option Explicit On
Option Strict On
 
Imports System
Imports System.Runtime.InteropServices
Imports Microsoft.Win32
 
Public Class Program
 
    Private Shared m_assInfo As System.Reflection.Assembly = Nothing
    Private Shared m_title As System.Reflection.AssemblyTitleAttribute = Nothing
 
    <DllImport("User32.dll")> _
    Public Shared Function ShowWindowAsync(ByVal hWnd As IntPtr, ByVal swCommand As Integer) As Integer
    End Function
 
 
    Private Shared Sub OnShutDown(ByVal sender As Object, ByVal e As SessionEndingEventArgs)
        Dim reason As SessionEndReasons = e.Reason
 
        If reason = SessionEndReasons.SystemShutdown Then
        End If
 
    End Sub
    Private Shared Sub HookSystemEvents()
        AddHandler Microsoft.Win32.SystemEvents.SessionEnding, New Microsoft.Win32.SessionEndingEventHandler(AddressOf OnShutDown)
    End Sub
 
    <STAThread()> _
    Public Shared Sub Main(ByVal args() As String)
        m_assInfo = System.Reflection.Assembly.GetEntryAssembly
        m_title = CType(m_assInfo.GetCustomAttributes(GetType(System.Reflection.AssemblyTitleAttribute), False)(0), Reflection.AssemblyTitleAttribute)
 
        Dim RunningProcesses As Process() = Process.GetProcessesByName(m_title.Title.ToString)
        Try
            '// Hook up the system
            HookSystemEvents()
        Catch ex As Exception
            MessageBox.Show("Hook up system faild!" & vbNewLine & vbNewLine & _
                "Contact system developers!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Environment.Exit(1)
        End Try
 
        Try
            '// Get assembly information
            m_assInfo = System.Reflection.Assembly.GetEntryAssembly
            m_title = CType(m_assInfo.GetCustomAttributes(GetType(System.Reflection.AssemblyTitleAttribute), False)(0), Reflection.AssemblyTitleAttribute)
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Environment.Exit(1)
        End Try
 
 
        Dim showConsole As Boolean = False
        Dim startServer As Boolean = False
 
        If Not args Is Nothing AndAlso args.Length > 0 Then
            Dim myArgs() As String = Nothing
 
            Try
                '// Split up the argumnets
                myArgs = args(0).Split(CChar(","))
            Catch ex As Exception
                MessageBox.Show("Argument split faild", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop)
                Environment.Exit(1)
            End Try
 
            '// Check number of arguments
            If myArgs.Length <> 2 Then
                MessageBox.Show("Wrong number of arguments", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop)
                Environment.Exit(1)
            End If
 
            Try
                '// Get arumnets
                showConsole = CBool(myArgs(0))
                startServer = CBool(myArgs(1))
            Catch ex As Exception
                MessageBox.Show(ex.ToString, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop)
                Environment.Exit(1)
            End Try
        End If
 
 
        Try
            '// Start/Open application
            If RunningProcesses.Length = 0 Then
 
                Application.EnableVisualStyles()
                Application.SetCompatibleTextRenderingDefault(False)
 
                DevExpress.UserSkins.OfficeSkins.Register()
                DevExpress.Skins.SkinManager.EnableFormSkins()
 
                Application.DoEvents()
                Application.Run(New MyContext(showConsole, startServer))
            Else
                ShowWindowAsync(RunningProcesses(0).MainWindowHandle, ShowWindowConstants.SW_SHOWMINIMIZED)
                ShowWindowAsync(RunningProcesses(0).MainWindowHandle, ShowWindowConstants.SW_RESTORE)
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Environment.Exit(1)
        End Try
    End Sub
 
    Private Enum ShowWindowConstants
        SW_HIDE = 0
        SW_SHOWNORMAL = 1
        SW_NORMAL = 1
        SW_SHOWMINIMIZED = 2
        SW_SHOWMAXIMIZED = 3
        SW_MAXIMIZE = 3
        SW_SHOWNOACTIVATE = 4
        SW_SHOW = 5
        SW_MINIMIZE = 6
        SW_SHOWMINNOACTIVE = 7
        SW_SHOWNA = 8
        SW_RESTORE = 9
        SW_SHOWDEFAULT = 10
        SW_FORCEMINIMIZE = 11
        SW_MAX = 11
    End Enum
End Class
 
 
Imports System
Imports System.Windows.Forms
Imports Microsoft.Win32
 
Public Class MyContext
    Inherits ApplicationContext
 
    Private WithEvents hkFrm As HotKeyFormHelper
    Private Declare Function GetForegroundWindow Lib "user32" Alias "GetForegroundWindow" () As IntPtr
    Private Declare Function SetForegroundWindow Lib "user32" Alias "SetForegroundWindow" (ByVal handle As IntPtr) As Integer
 
    Public Sub New(Optional ByVal showConsole As Boolean = False, Optional ByVal startServer As Boolean = False)
        frmConsole.ShowForm()
 
        hkFrm = New HotKeyFormHelper()
 
        '// Hotkey: Ctrl-Shift-0 (zero) with unique ID = 0
        hkFrm.RegsiterHotKey(0, HotKeyFormHelper.HotKeyModifiers.Control Or HotKeyFormHelper.HotKeyModifiers.Shift, Keys.D1)
 
        '// Show console form
        If showConsole Then frmConsole.ShowForm()
    End Sub
 
    Private Sub hkFrm_HotkeyPressed(ByVal ID As Integer) Handles hkFrm.HotkeyPressed
        Select Case ID
            Case 0
                If frmConsole.instance.WindowState = FormWindowState.Minimized Then
                    frmConsole.instance.WindowState = FormWindowState.Normal
                End If
                Application.DoEvents()
                If Not GetForegroundWindow.Equals(frmConsole.instance.Handle) Then
                    SetForegroundWindow(frmConsole.instance.Handle)
                End If
        End Select
    End Sub
 
End Class

Open in new window

0
 
AWestEngAuthor Commented:
Hi Idle_Mind!
So I now I have added the DevExpress to the Application Event and that works fine.
 Now to how I should start upp the application and handle shutdowns from outside
I now start frmConsole instead of Sub Main so what should I add to the form?
And how do I pass parameter to the applicaiton without sub Main?

Namespace My
    Partial Friend Class MyApplication
 
        Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
            DevExpress.UserSkins.OfficeSkins.Register()
            DevExpress.Skins.SkinManager.EnableFormSkins()
        End Sub
 
    End Class
End Namespace

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
You can get the command line arguments using the "e" parameter in the Application Events.

Note that below, in the StartupNextInstance() event, we are sending the parameters to a TextBox on Form1.  This assumes that Form1 is the startup form and there the default instance would be showing.
    Partial Friend Class MyApplication
 
        Private Sub MyApplication_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
            For Each param As String In e.CommandLine
                Debug.Print(param)
            Next
        End Sub
 
        Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
            For Each param As String In e.CommandLine
                Form1.TextBox1.AppendText(param & vbCrLf)
            Next
        End Sub
 
    End Class

Open in new window

0
 
Mike TomlinsonMiddle School Assistant TeacherCommented:
Looking at the old code...you could put ALL of the HotKey code INSIDE the main form of your application now.  You wouldn't need a separate helper form/class anymore.
0
 
AWestEngAuthor Commented:
Thx m8, it looks great. :).
I'll will check to code tomorrow and get back to you, it's almost midnight here in Sweden now (23:32) and it's workday tomorrow so I'm off for today ..  
 Thx again, I really appreciate your help,
0
 
AWestEngAuthor Commented:
And it worked perfect!! THX!!!! :).
You know your .Net really good. thx again m8...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.