People have been asking me over and over: how can I run an external program from within a Delphi program? Can I print documents from within my program, without explicitly starting the application that created the document, such as: print a Word-document without starting Word? How to open my browser with a local HTML page? How to surf to a site, i.e. open an external HTML page with a Delphi app?
And: how can I make my 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
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: ShellExecuteEx or CreateProcess.
The simplest method is: start the external application with ShellExecuteEx and then monitor the process handle with WaitForSingleObject.
I wrapped it all up in a ready-to-go demo project (see picture above), which 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 program accepts one or more parameters, you can enter these 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.
You can download the executable of the demo as EXEWDEMO.ZIP. You can also download EXEWAIT.ZIP, the fully commented source code files for this project. Have a look in our download section, under "Mini Tutorial Projects".
FAQ Crash Course Delphi Tips Source Code Downloads Links
© Copyright 1999-2019