Solved

Get application Shutdown event when using a context class

Posted on 2008-10-07
23
502 Views
Last Modified: 2013-11-07
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
0
Comment
Question by:AWestEng
  • 12
  • 7
  • 2
  • +1
23 Comments
 
LVL 7

Expert Comment

by:nsanga
ID: 22658244
have you tried defining a handler for ApplicationExit in MyContext constructor as below


AddHandler Application.ApplicationExit, AddressOf OnApplicationExit
0
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 22658256
you need to handle formclosing event of MyContext (assuming it is a form). in closing event, check for e.closereason..
0
 
LVL 1

Author Comment

by:AWestEng
ID: 22658294
MyContext is no form its a Context class
0
Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

 
LVL 1

Author Comment

by:AWestEng
ID: 22658333
does Application.ApplicationExit cast an event for all types of shutdowns? even if I terminate the application  process from outide
0
 
LVL 1

Author Comment

by:AWestEng
ID: 22658374
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
 
LVL 7

Expert Comment

by:nsanga
ID: 22658391
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
 
LVL 13

Expert Comment

by:SameerJagdale
ID: 22658405
0
 
LVL 1

Author Comment

by:AWestEng
ID: 22658632
the SessionEnding doesn't work either
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22662456
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22662478
Since your app doesn't have an interface...how exactly would one close your app in a "controlled" fashion anyways?...  =\

0
 
LVL 1

Author Comment

by:AWestEng
ID: 22662553
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22662558
but that my be the same, I don't know. :)
0
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22662627
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22662851
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22663245
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22667152
oki. I will paste the code I use to day, 2 sec
0
 
LVL 1

Author Comment

by:AWestEng
ID: 22667209
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22676808
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22681776
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
 
LVL 85

Expert Comment

by:Mike Tomlinson
ID: 22681781
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
 
LVL 85

Accepted Solution

by:
Mike Tomlinson earned 500 total points
ID: 22681964
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22682667
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22690231
And it worked perfect!! THX!!!! :).
You know your .Net really good. thx again m8...
0

Featured Post

Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question