Using ShellExecute

Use Shell or CExecutive to run other people’s programs when you know what you’re doing. But when only the user knows what you’re doing you might find ShellExecute more convenient. For example, if you want to let Windows decide how to process a document, you can pass the document name to ShellExecute. In the Test Execute program, you can try this by setting the mode to VBShell­Execute, typing a document filename in the Arguments field, and leaving the Program field blank.

ShellExecute has a lot of arguments, most of which have defaults. This sounds like a case for optional arguments; check out VBShellExecute in PROCTOOL­.BAS. You pay a performance price for the extra convenience of ShellExecute, so don’t call it when you don’t need it.

Unlike Shell and CExecutive, ShellExecute doesn’t search the PATH environment variable for your program. If you’re passing it an executable file, you need to search the path yourself by calling SearchForExe (in UTILITY.BAS). It calls the SearchDirs function described in “SearchPath” in Chapter 5. ShellExecute returns what the documentation claims is an instance handle, but isn’t. Whatever it is, you can’t use it to tell when a process has terminated. Never mind. You usually call ShellExecute in response to a user selecting a document. If you don’t even know which program will process the document, you’re probably not going to depend on the results. Therefore, the Wait option is disabled in the Test Execute program when the VBShellExecute mode is active.

When All Else Fails, Hit It with a Hammer

If the techniques described in this section seem too complex, try this low-tech batch file solution. Your calling program can create a batch file. The batch file creates a temporary file, calls the target program, and then deletes the temporary file. You write the batch file to disk, run it, and then periodically check to see whether the temporary file still exists. When the temporary file disappears, your program is finished and you can delete the batch file.