The name of the actual class (ThreadWatcher) is misleading, sorry about that.
Currently, the class will accept either a file to launch/monitor or a process to attach to. The whole purpose of the monitor is to allow you to hook onto a process and watch it and restart it if it ends.
Currently, it does not get any text back (if it's a console application) because there's no handles for it but it's on the ToDo list.
Enough of me yammering, Here's the code:
vb.net Code:
Public Class ThreadWatcher 'Variables Private WithEvents m_Thread As Process Private Executable As String = String.Empty Private Running As Boolean = False 'Events Public Event Terminated() Public Event ThreadError(ByVal errorMsg As String) ''' <summary> ''' Create a new instance of the class. ''' </summary> ''' <param name="filename">The file to launch.</param> ''' <remarks></remarks> Public Sub New(ByVal filename As String) Executable = filename End Sub ''' <summary> ''' Create a new instance of the class. You don't need to call Start() here! ''' </summary> ''' <param name="process">The process to monitor.</param> ''' <remarks></remarks> Public Sub New(ByVal process As Process) Executable = String.Empty m_Thread = process m_Thread.EnableRaisingEvents = True Executable = m_Thread.MainModule.FileName ' :D Running = True End Sub ''' <summary> ''' Start the Process. ''' </summary> ''' <remarks></remarks> Public Sub Start() If Running = True Then RaiseEvent ThreadError("This Thread Watcher is already in use: " & m_Thread.MainWindowTitle) : Exit Sub If Executable <> String.Empty Then m_Thread = New Process With {.StartInfo = New ProcessStartInfo(Executable), .EnableRaisingEvents = True} If IO.File.Exists(Executable) Then m_Thread.Start() Else RaiseEvent ThreadError("The file does not exist!") : Exit Sub Running = True End Sub ''' <summary> ''' Restart the Process. ''' </summary> ''' <remarks></remarks> Public Sub Restart() Call Start() End Sub ''' <summary> ''' Stop the Process. ''' </summary> ''' <remarks></remarks> Public Sub StopProcess() Try m_Thread.Kill() Catch ex As Exception RaiseEvent ThreadError(ex.Message.ToString) End Try End Sub Private Sub m_Thread_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles m_Thread.Exited Running = False RaiseEvent Terminated() End Sub ''' <summary> ''' Returns a True or False if the process is active or not. ''' </summary> ''' <returns></returns> ''' <remarks></remarks> Public Function Active() As Boolean Return Running End Function ''' <summary> ''' Dispose of the class. Probably could be managed better, but whatever.... ''' </summary> ''' <remarks></remarks> Public Sub Dispose() m_Thread.Close() m_Thread.Dispose() Me.Finalize() End Sub End Class
Questions, comments, and criticism are welcome. The code is available for all to use, and credit isn't required but welcome.
