Browse DevX
Sign up for e-mail newsletters from DevX


Launching and Monitoring External Programs from VB.NET Applications : Page 4

You no longer need to use the Win32 API or the VB Shell function to launch external applications. Instead, use the System.Diagnostics.Process class built into the .NET framework to simplify your code.

Detecting When a Process Exits
In VB6, you could call the Win32 API's GetModuleUsage() function to determine when the process ended. The.NET equivalent is to loop repeatedly after launching the process, checking the Process.HasExited property and calling the Application.DoEvents method to handle other events in your application until the process ends.

Do While Not myProcess.HasExited



But the Process class gives you a cleaner way to determine when the process exits—it can raise an Exited event. To make this happen, you need to set the Process.EnableRaisingEvents property to True (by default, the property is False), and create an event handler. For example:

   ' allow the process to raise events
   myProcess.EnableRaisingEvents = True
   ' add an Exited event handler
   AddHandler myProcess.Exited, _
      AddressOf Me.ProcessExited
   ' start the process
   ' event handler
   Friend Sub ProcessExited(ByVal sender As Object, _
      ByVal e As System.EventArgs)
      Dim myProcess As Process = DirectCast( _
         sender, Process)
      MessageBox.Show("The process exited, raising " & _
         "the Exited event at: " & myProcess.ExitTime & _
         "." & System.Environment.NewLine & _
         "Exit Code: " & myProcess.ExitCode)
   End Sub
One potential problem with both of these methods is that if the launched process hangs or never exits, your application is stuck. One solution is to add a timer that fires periodically, and checks to see if the launched application is still responding.

Thanks for your registration, follow us on our social networks to keep up-to-date