Browse DevX
Sign up for e-mail newsletters from DevX


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

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.

Launch Invisible Processes
You don't have to launch a process in a visible window; sometimes you just want to run a process and retrieve the output. The following example changes to the System folder, and then runs a DOS dir command with the file specification "*.com" which gives you a directory listing of the files in that folder with a .com extension. On Windows XP, the command shell interpreter recognizes the "&&" operator as a command separator, so you can place multiple commands on a single line. The ">>" operator redirects output into a named file. In this case, the code pipes the dir command results into the file "dirOutput.txt" in the path designated by the Application.StartupPath property.
   Dim myProcess As Process = New Process()
   Dim s As String
   Dim outfile As String = Application.StartupPath & _
   ' get the System path
   Dim sysFolder As String = _
      System.Environment.GetFolderPath _
   ' set the file name and the command line args
   myProcess.StartInfo.FileName = "cmd.exe"
   myProcess.StartInfo.Arguments = "/C cd " & _
      sysFolder & " && dir *.com >> " & Chr(34) & _
      outfile & Chr(34) & " && exit"
   ' start the process in a hidden window
   myProcess.StartInfo.WindowStyle = _
   myProcess.StartInfo.CreateNoWindow = True
   ' if the process doesn't complete within
   ' 1 second, kill it
   If Not myProcess.HasExited Then
   End If
   ' display exit time and exit code
   MessageBox.Show("The 'dir' command window was " & _]
      "closed at: " & myProcess.ExitTime & "." & _
      System.Environment.NewLine & "Exit Code: " & _
The preceding code returns an ExitCode value of zero (0). To see an example of a non-zero ExitCode, append an "X" or some other character to the System folder path to make it invalid. That causes an error, and the ExitCode value will be different. Because a process with an error could potentially run forever, the code uses an overloaded WaitForExit method that accepts a number of milliseconds to wait before returning control to the launching program. The preceding code waits for 1 second before ending the launched process by calling the Kill method, which forces the process to exit. Check for the existence of the dirOutput.txt file in your application's startup directory to see the results.

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