Recipe 11.7 Run the Application Associated with a Data File

11.7.1 Problem

You'd like to find a way to provide a list of existing files, allow users to select a file, and run the appropriate application for that file. Windows knows how to do this?for instance, when you double-click on a file with a .TXT extension in Explorer, Windows runs Notepad with that file. How can you provide this sort of functionality in your own applications?

11.7.2 Solution

Windows provides two API functions, FindExecutable and ShellExecute, that make running a related application possible from within Access. Both functions rely heavily on the Windows registry, which tracks the relationships between filename extensions and related executable programs. Figure 11-8 shows the results of running the REGEDIT.EXE program, which ships as part of Windows. REGEDIT allows you to add, edit, modify, or delete file associations. (The registry editor is named REGEDT32.EXE under Windows NT and, though it looks different, it functions in a similar manner.)

Figure 11-8. REGEDIT.EXE, showing file types registered on a typical system

Be sure not to change any of the entries in the registry when looking through REGEDIT.

In this solution, you use the FindExecutable function to get the name of the executable file associated with a selected data file. You also use the ShellExecute function to run the executable file, with the selected data file opened and ready to edit.

Load and run frmTestExecute, shown in Figure 11-9. To use this form, select a path (it defaults to your Windows directory when it first loads). Once the list box fills with all the files in the specified directory, click on one with the mouse. If there's an active file association for the selected file, the form will display that executable filename in a text box. If there's an associated executable file, you can run it and load your chosen file by double-clicking on the list box or clicking on the checkmark button.

Figure 11-9. The sample form, frmTestExecute, from 11-07.MDB

To use this functionality in your own applications, follow these steps:

  1. Import the module basShellAPI from 11-07.MDB into your application.

  2. To find the executable file associated with a given document, use the FindExecutable API function (aliased as acb_apiFindExecutable in the code). Call it with the three parameters described in Table 11-5.

Table 11-5. Parameters for the FindExecutable API function






The filename that has an association in the registration database



The drive letter and path for the default directory (you can use "." to indicate the current directory)



A buffer to contain the returned executable name

The FindExecutable function returns an integer error code. If the value is greater than 32, the function has succeeded. Otherwise, it returns one of the error codes in Table 11-6 (note that these error codes are shared by several functions). If the function succeeded, strResult will be a null-terminated string containing the associated executable file. You'll need to trim off that trailing null character. One easy way to do this is by using the TrimNull function in basShellAPI, as follows:

Private Function TrimNull(strValue As String)

    ' Trim strValue at the first
    ' null character you find.
    Dim intPos As Integer
    intPos = InStr(strValue, vbNullChar)
    If intPos > 0 Then
        TrimNull = Left$(strValue, intPos - 1)
        TrimNull = strValue
    End If
End Function

Table 11-6. Some shared error codes for FindExecutable and ShellExecute




System error occurred


File not found


Path not found


Sharing violation occurred


Not enough memory to start the task


Association incomplete


No association in the Registration Database for the file extension


DLL not found

For example, the following code will find the executable file associated with MyFile.OOG:

Dim strBuffer As String
Dim strResult As String

strBuffer = Space(128)
strResult = ""

intRetval = acb_apiFindExecutable("MyFile.OOG", ".", strBuffer)
If intRetval > acbcHinstanceErr Then
   ' Use the TrimNull function in basShellAPI
   ' to remove the trailing null character.
   strResult = TrimNull(strBuffer)
End If
' Now, strResult holds either "" or the name 
' of the executable you need.

To make this simpler, basShellAPI includes the acbFindExecutable function. This function requires the same parameters and returns the same values as acb_apiFindExecutable, but it handles the details of initializing the string buffer and trimming off the trailing null character for you. You'll want to use this function instead of calling the Windows API directly, as it will ensure that you use the correct methods for sending and receiving strings.

Once you know the name of the executable file associated with the selected document, you'll want to execute it with the ShellExecute API function. You could, of course, use the Shell command, but ShellExecute gives you a bit more flexibility, as a comparison of the two shows:

  • ShellExecute returns an error code if something goes wrong, but Shell requires that you write error-handling code to trap and deal with errors. In the long run, using ShellExecute is simpler.

  • ShellExecute allows you to specify the default drive/directory for your application. Shell does not.

  • ShellExecute provides a few more options than Shell; see Table 11-8 for details.

  • Not that you'll use it often, but ShellExecute allows you to specify the action to take on opening a file. If you want to print the file rather than open it, specify the "print" operation for the second parameter.

If your only intent is to run the executable associated with a file, you don't need to call FindExecutable explicitly. Instead, you can pass the file name to ShellExecute, and it will find the executable for you. In this example, we wanted to display the associated executable, so we divided the task into two API function calls.

To use the ShellExecute function, call it with the six parameters shown in Table 11-7.

Table 11-7. Parameters for the ShellExecute API function






The handle of the window to be used as the parent for message boxes that may appear.



The operation to perform. Normally, can only be "open" or "print".



The name of the program to start.



Command-line arguments for the executable program. Normally, the name of the file to load into the application.



The default drive/directory for the application when it starts up.



Specification of how to show the new window when the application starts up. For a list of values, see Table 11-8.

Table 11-8 lists all the possible values for the intShowCmd parameter. These values control how the new application's window appears on the Windows desktop.

Table 11-8. Window display options for the intShowCmd parameter to ShellExecute






The window is hidden when started.



The window is restored to its previous state (neither minimized nor maximized).



The window is made visible and minimized.



The window is made visible and maximized.



The window is displayed, but doesn't gain the input focus.



The window is minimized (as an icon) when started.



The window is made visible and minimized, but doesn't receive the input focus.



The window is displayed without any change to the window's state (remains minimized, normal, or maximized).



The window is restored to its previous state (neither minimized nor maximized). (Same as acbSW_SHOWNORMAL.)

For example, to run the program C:\OOGLY\MKOOGLE.EXE (which created MyFile.OOG) maximized on the screen, you could run code like this from a form's module:

intRetval = acb_apiShellExecute(Me.hWnd, "open", "C:\OOGLY\MKOOGLE.EXE", _

11.7.3 Discussion

You can call the FindExecutable function to retrieve an associated executable file for a given document, and then pass both the executable name and the document name to ShellExecute to load them. For example, you might use code like this in your application:

Dim intRetval As Integer
Dim strBuffer As String

intRetval = acbFindExecutable("MyFile.XXX", ".", strBuffer)
If intRetval <= acbHInstanceErr Then
   MsgBox "Unable to find executable. Error " & intRetval & "."
   ' You're only here if you found the executable.
   intRetval = acb_apiShellExecute(Me.hWnd, "open", strBuffer, _
      "MyFile.XXX", "C:\NewDocs", acbSW_SHOWMAXIMIZED)
   If intRetval <= acbHInstanceErr Then
      MsgBox "Unable to load application. Error " & intRetval & "."
   End If
End If

You may find it interesting to work your way through the sample form frmTestExecute. It uses the AddItem method of the ListBox control (added in Access 2002) to add file names retrieved from a Collection object. The code fills the collection by calling the FillDirlist method, in the basFillList module.

The methods presented in this solution rely heavily on the Windows registry. It may be useful to dig through the file associations in the registry (as discussed in the earlier sidebar) and see how Windows finds applications itself when you double-click on data files.

If you're using Windows 98 or Windows Me, you'll need to take into consideration file and path names that include embedded spaces. Windows 2000, Windows XP, and later operating systems handle spaces in file names without any trouble. For earlier operating systems, make sure you surround file and path names that include spaces with quote marks (Chr$(34)) in order to ensure proper handling when you call the ShellExecute API function.