Using The ShellExecute API to open programs and files


Download The Sample Code 
Return to the HOWTOs

Visual basic has a built in function called shell. This function allows you to spawn an application. However, window's has a built in API call which is much more powerful than VB's shell command. This API call allows you to run any program you want, and it also allows you to open any file with its associated program. This API is the ShellExecute API.

So how do you use the ShellExecute API? First you have to declare it. To do this you can either run the API Viewer which comes with some versions of Visual Basic, or you can just copy the following line into your document. When I work with APIs, I prefer to put them in a separate module, but that is completely up to you.

Here is the declaration for ShellExecute:

Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" _



    (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _



    ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd _



    As Long) As Long

How do you call ShellExecute? While if you want to find out all the details, you can look it up in the help. Otherwise, basically all you need to know is that lpFile is the filename or program name you wish to open, and that nShowCmd should probably be set to SW_SHOWNORMAL. With that in mind, the I wrote a public sub in my module called RunProgram:

Public Sub RunProgram(strProgram As String)



    Dim lRet As Long    ' Get the return value



    



    ' Execute the API call



    lRet = ShellExecute(vbNull, "", strProgram, "", "", SW_SHOWNORMAL)



    



    ' If ShellExecute works it will return a number greate than 32



    ' Otherwise call our ReportError function to see what went wrong



    If lRet <= 32 Then



        MsgBox "Error Running Program"



    End If



End Sub            

As you can see from the comments, if ShellExecute returns a value <= 32 then an error has occurred. In my sample code, I show you a program sub that I call to find out what the exact error was. So if you want to have better error handling download the code and check it out.

Now the RunProgram sub works the exact same as if you went to the start menu and choose run. It will either run the program specified, or it will run the associated program for a given file. Some fun ones to try out are:

  • calc.exe
  • http://www.microsoft.com
  • mailto:billgates@microsoft.com
  • c:\test.doc - but first create a word document and save it as c:\test.doc

Download The Sample Code - See my error handling sub
Return to the HOWTOs