Running an external application (and waiting) 

A DelphiLand Tutorial

How to launch external program from within your Delphi program? How to print documents from within your program, without explicitly starting the application that created the document? How to open your browser with a local HTML page? How to open an external HTML page ("surf" to a site)?

And: how to make your Delphi program wait until the external program is terminated?

For just running an external application (or opening a registered file, opening a folder, printing a file, and so on), there are several functions available. In most cases, the Windows API-function ShellExecute is used. It gives some degree of control, and at the same time it's not too complicated. A few examples:


Launching an external program and waiting until it is terminated is quite another story...
We can tell if a process has completed by monitoring its process handle. That process handle can be obtained by using one of two Win32 API-functions to start the external program: CreateProcess or ShellExecuteEx.

The simplest method is: start the external application with ShellExecuteEx and then monitor the process handle with WaitForSingleObject.

The demo project demonstrates the use of the functions discussed above. To make it easier to see what is happening, we made the window of the demo stay on top of all other windows. Clicking the first button will launch the external application that is specified in the first edit-box. If that application can accept parameters, such as the name of a file to open, you can enter the parameter(s) in the second edit-box. What happens next, depends from the state of the "Wait for termination" checkbox:

A click on the second button prints the file whose name is in the edit-box above it.

And when you click on one of the underlined labels, an HTML file will be loaded in your browser: either this tutorial, or DelphiLand's home page. Note the added extra touch: when you hover your mouse cursor over a simulated hyperlink, the cursor will change, just as with a real hyperlink in a browser!

Finally, if an error occurs, such as specifying to run a non-existent program, or print a file that doesn't exist on your system, then an appropriate error message will show up.

© Copyright 1999-2002
Studiebureau Festraets