Visual Basic/External Processes

It is often the case that a program already exists to do some job so rather than rewrite the program in Visual Basic it is more efficient to run the existing program from Visual Basic. This can work very well for command line programs or scripts written in any language.

The general scheme is to create a string containing the command line, call a function to run it and then wait for the command to complete. There are many refinements that can be made including all sorts of ways of sending data to the new process, reading results from it, pausing it, setting its priority and so on.

The Shell Function
The simplest way of running an external program is to do something like this:

Shell is a built in Visual Basic function that executes a command line and returns a handle to that process. Shell takes an optional argument that controls the window style of the new process (maximized, normal, hidden, etc.).

Unfortunately running another program like this doesn't give you much control over what is happening. In particular, there is no obvious way to find out if the program has completed its work.

Luckily Shell actually does slightly more than launch the program. It also returns the process id. This is the number displayed by Task Managers and can be used to check the status of the process. Unfortunately, as is so often the case with Visual Basic and Windows, there is no built in function nor even a single API function that can use it directly. Therefore, we must write a little more code. First, we must declare a few API functions and constants:

Here is an example of a function that executes a command and waits for it to complete:

Call it like this:

Exercises

 * Modify the ShellWait example function so that the caller can distinguish between failure to launch the process and timeout.
 * Suggest a reason why this might be a good idea.