Solved

Get application Shutdown event when using a context class

Posted on 2008-10-07
23
496 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
 
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

747 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now