Hi guys...

I was trying to find a way to detect the starting and stopping of an external application. So, I did a quick search and found the solution from here itself.

And I think, it would be better to post it here so that others could also make use of it.

vb.net Code:
  1. Public Class Form1
  2.     Dim myProcess As Process    '~~~ Our object that references the process we want to start
  3.  
  4.     '~~~ Start
  5.     Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
  6.         myProcess = New Process                         '~~~ Creating the object
  7.         myProcess.StartInfo.FileName = "notepad.exe"    '~~~ We are going to start notepad.
  8.         myProcess.Start()                               '~~~ Start it
  9.  
  10.         myProcess.EnableRaisingEvents = True            '~~~ Need to be TRUE, inorder to notify us when the process is closed by the user in some other means (like Alt + F4)
  11.         AddHandler myProcess.Exited, AddressOf ProcessExited    '~~~ When the process is exited, the sub "ProcessExited" will be called
  12.     End Sub
  13.  
  14.     '~~~ Stop
  15.     Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  16.         If myProcess IsNot Nothing Then             '~~~ Check if we have started the process or not
  17.             If myProcess.HasExited = False Then     '~~~ Check if the process is already exited or not
  18.                 myProcess.CloseMainWindow()         '~~~ If not, try to close it
  19.  
  20.                 myProcess.WaitForExit(1000)         '~~~ Wait for 1000 millisecconds allowing it to close
  21.  
  22.                 If myProcess.HasExited = False Then '~~~ If the process haven't closed yet (even after waiting), then we are going to force it to close
  23.                     myProcess.Kill()
  24.                 End If
  25.             End If
  26.         End If
  27.     End Sub
  28.  
  29.     '~~~ This is the sub which will be called when the Process is closed. Whatever we want to do (when the process is closed), has to be included in this sub
  30.     Private Sub ProcessExited(ByVal sender As Object, ByVal e As System.EventArgs)
  31.         MessageBox.Show("Hey dude, you were using this program for XX minutes ! Oh man !!! You are so addicted to this program...! You closed the program at: " & myProcess.ExitTime)
  32.  
  33.         myProcess.Close()   '~~~ Freeup the object
  34.     End Sub
  35. End Class
Hope this helps...

Starting of the application will be done through our program. And when the user closes the program, it would notify you.

Thanks to: