Tuesday, March 13, 2012

VB .NET Auto Restart application after it is clash


Concept :
- create two window form
- 1st form will act as a watchdog program to watch the 2nd form
- if the 2nd form clashed or closed, it will auto start back the 2nd form.
- when 2nd form Disposed will close the 1st form

'******
'Form1
'******
Public Class form1
Public Sub New()
InitializeComponent()
Application.EnableVisualStyles()
Dim frm As New form2()
AddHandler Application.ThreadException, AddressOf frm1.UnhandledThreadExceptionHandler
Application.Run(frm)
End Sub
End Class



'******
'Form2
'******
Imports System.Threading

Public Class form2
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Simulate Exception
If 1 + "A" Then
End If
End Sub

Public Sub UnhandledThreadExceptionHandler(ByVal sender As Object, ByVal e As ThreadExceptionEventArgs)
Me.HandleUnhandledException(e.Exception)
End Sub

Public Sub HandleUnhandledException(ByVal e As Exception)
Application.Restart()
End Sub

Private Sub frmSecond_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
form1.Close()
End Sub
End Class

No comments: