AWestEng
asked on
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
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
you need to handle formclosing event of MyContext (assuming it is a form). in closing event, check for e.closereason..
ASKER
MyContext is no form its a Context class
ASKER
does Application.ApplicationExi t cast an event for all types of shutdowns? even if I terminate the application process from outide
ASKER
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
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.......
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.......
ASKER
the SessionEnding doesn't work either
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...
http://msdn.microsoft.com/en-us/library/ms686714(VS.85).aspx
You can't trap this...
Since your app doesn't have an interface...how exactly would one close your app in a "controlled" fashion anyways?... =\
ASKER
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
dim test as Process
------
test .Start
test.Kill
ASKER
but that my be the same, I don't know. :)
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. =\
ASKER
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,?
can I use something else then Process to start an application that will add a better way to kill the app,?
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. =)
https://www.experts-exchange.com/questions/23724631/Start-application-without-form-open-form-when-pressing-F1.html
Thoughts?...
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. =)
https://www.experts-exchange.com/questions/23724631/Start-application-without-form-open-form-when-pressing-F1.html
Thoughts?...
ASKER
oki. I will paste the code I use to day, 2 sec
ASKER
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.Offic eSkins.Reg ister( ) DevExpress.Skins.SkinManag er.EnableF ormSkins()
any tips how to redesign this? :)
I really appreciated that you are helping me Idle_Mind thx m8 :)
DevExpress.UserSkins.Offic
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
ASKER
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?
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
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.
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
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.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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,
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,
ASKER
And it worked perfect!! THX!!!! :).
You know your .Net really good. thx again m8...
You know your .Net really good. thx again m8...
AddHandler Application.ApplicationExi