Shell Execute API

in Visual Basic®

by Rick Meyer

Home

With the ShellExecute API you can run another program from VB. Also: Open, Print or Play any given file using the program associated with the file. In this demo we are shelling an HTML file which will automatically launch your default browser and show the page in it.
Note that files are associated with different commands. (see Start->Settings->Folder Options->File Types)

Here the "open" command is used. This will launch the file. If you use "play" you can play songs/movies. You can use "print" to open the file in the program associated with it and automatically preform the associated "print" command.

Now you are ready for the code. Select all of the following code (by clicking on the word 'Option' three times) and copy it to the clipboard [Ctrl][Insert]. Then paste it into the code window of Form1 with [Shift][Insert]. Variable Key
% As Integer
& As Long
! As Single
# As Double
$ As String
Option Explicit

'========================================================
'   API declaration
'========================================================
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

Private Sub Form_Load()
    Dim sFile As String
    Dim sCommand As String
    Dim sWorkDir As String
    
    sFile = "C:\albums\index.html"  'The file to execute
    sCommand = vbNullString         'Command line parameters
    sWorkDir = "C:\albums"          'The working directory

    ShellExecute hwnd, "open", sFile, sCommand, sWorkDir, 1
End Sub