Title | Use the ShellExecute API function to execute a file, launch the Find utility, and perform default actions |
Keywords | ShellExecute, start, execute, find, open, default action |
Categories | Windows, API |
|
result = ShellExecute( _
Me.hWnd, cboOperation.Text, _
txtFile.Text, txtParameters.Text, _
txtDirectory.Text, show_style)
|
Note that not all of these operations are defined for all types of files. For example, the print command only works with document files.
While commands such as open and edit sound like they would be simpler, they are more confusing. To determine whether one of these commands will work for a particular type of file, open Windows Explorer. In the Tools menu, select Folder Options and click on the File Types tab. Find the file type and click on it. Then click the Edit button. Look for the commands under Actions. Click one and click Edit to see the action's definition. On my system, for example, the Text Document file type has an open command that invokes the application "C:\Program Files\Accessories\Wordpad.exe" (I changed it from Notepad). There is no edit action so using that command with ShellExecute generates a "No associated application" error.
Some particularly useful combinations include:
- Open a folder in a folder view:
ShellExecute hWnd, "open", "C:\whatever", _
vbNullString, vbNullString, SW_SHOWNORMAL
- Explore a folder with Windows Explorer:
ShellExecute hWnd, "explore", "C:\whatever", _
vbNullString, vbNullString, SW_SHOWNORMAL
- Launch the Find utility from a particular directory:
ShellExecute hWnd, "find", "C:\whatever", _
vbNullString, vbNullString, SW_SHOWNORMAL
- Display a Web page in the system's default browser:
ShellExecute hWnd, "open", "C:\whatever\test.html", _
vbNullString, vbNullString, SW_SHOWNORMAL
Note that you can also execute programs using Visual Basic's Shell function. See Start another program using Shell for more information.
As a final note, ShellExecute is a good example of a function that is being asked to perform too many different tasks. Internally these tasks may be related, but to the programmer executing a program, launching a search window, and exploring a folder are not closely related tasks. The fact that this routine has an operation parameter is one hint that it may be doing unrelated chores. Another hint is the fact that it takes several different parameters that are used only under certain circumstances depending on the operation.
This sort of routine is unnecessarily complex, making it hard to program, debug, and maintain. Perhaps this is part of the reason Windows NT contains 14 million lines of code and a large number of bugs.
It would have been better to make several separate routines that used only the parameters they actually needed. If they have common needs behind the scenes, they could call the same support subroutines.
My book Bug Proofing Visual Basic has more to say about these kinds of routines and how to avoid them.
|