0

I want to detect if a target process has ended or not. I have written the expected sequence below:

  1. A process named TEST runs at the background.
  2. Status.Text = "Running" to indicate process is running.
  3. Process ends by itself.
  4. Status.Text = "Finished" right after the process ends.
testimonial
  • 93
  • 1
  • 1
  • 9

2 Answers2

1

Unfortunately, the solution posted here requires to be run as administrator.

A simple polling-solution using a timer could do the work just fine.
If you use a polling solution, then of course you have to re-read the processes inside the loop or polling event.
Use the process name without .exe here.

Private timer_watcher As Timer

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Me.Label1.Text = "Watching"
    Me.timer_watcher = New Timer
    AddHandler timer_watcher.Tick, AddressOf TimerEvent
    timer_watcher.Interval = TimeSpan.FromSeconds(1).TotalMilliseconds
    timer_watcher.Start()
End Sub

Public Sub TimerEvent(sender As Object, e As EventArgs)
    Dim p() As Process = System.Diagnostics.Process.GetProcessesByName("processname")
    If p.Length = 0 Then
        timer_watcher.Stop()
        Me.Label1.Text = "Stopped"
    End If
End Sub
Community
  • 1
  • 1
KekuSemau
  • 6,830
  • 4
  • 24
  • 34
  • Thanks! Your solution worked but "Me.timer_watcher = New Timer" needs to be removed, generates overload errors. Thanks! – testimonial May 11 '15 at 06:41
  • Well just to explain: The code works without using a Timer in the Designer. If you add it in the Designer, you can also set Interval and the Tick Method there. – KekuSemau May 11 '15 at 19:17
0

Consider using the Process.Exited event.

Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
  • Dim p As Process = New Process() I did this way, i can do p.HasExited – testimonial May 10 '15 at 18:51
  • @BerkayOzturk So... what's the problem? Check my comment above. – SomeNickName May 10 '15 at 18:53
  • @SomeNickName I want to display a message right after proccess exits, but dont know how to properly and continuously check if exited – testimonial May 10 '15 at 19:01
  • @BerkayOzturk Did you check my comment above? Process.WaitForExit() should do it? – SomeNickName May 10 '15 at 23:37
  • @SomeNickName I searched Process.WaitForExit() but dont really understand how to use it. Can you give me a quick example? – testimonial May 11 '15 at 06:03
  • @BerkayOzturk the remarks section on the [documentation](https://msdn.microsoft.com/en-us/library/fb4aw7b8%28v=vs.110%29.aspx) explains it quite good, but i'll short: It stops the current thread until the process exits, after the process exits it continues the thread execution. Meaning you can call it when you want to do something after the process exits, if you don't want to block the thread, you can use the Exited event as @ Zev Spitz suggested. – SomeNickName May 11 '15 at 14:50