Visual Basic Win32 Shell Routines
ShellExecute: ShellExecute Madness
     
Posted:   Monday October 26, 1998
Updated:   Monday December 26, 2011
     
Applies to:   VB4-32, VB5, VB6
Developed with:   VB5, Windows 98
OS restrictions:   None
Author:   VBnet - Randy Birch
     

Related:  

ShellExecute: Simulate a Hyperlink with a Label Control
FindExecutable: Find Exe Associated with a Registered Extension
CreateProcess: Start Separate Instances of the Default Browser

ShellExecute: Send Large Emails in Outlook Express
       
 Prerequisites
None.

Windows' file associations provide the easiest way to launch applications by passing just the path and filename of the item to open. At the centre of this functionality is the ShellExecute API.

The Windows 95, 98 and NT and later design guides stress that for an application to conform to the Windows Logo guidelines, execution of associated applications must be made using the ShellExecute API and not the CreateProcess API.  The rational for this is that under Windows NT and later, system administrators may have disabled or prevented users from opening or accessing specific file types. The ShellExecute API honours any restrictions while CreateProcess does not. 

ShellExecute takes six parameters, many of which are optional:

hWnd The Window handle to a parent window. This window receives any message boxes that an application produces. For example, an application may report an error by producing a message box. Typically this is the desktop (and is used as such in this routine).
lpOperation Specifies the action (verb) that will take place on execution. With the exception of null, these are passed as strings:
"Open" The function opens the file specified by the lpFile parameter. The file can be an executable file or a document file. It can also be a folder.
"Print" The function prints the file specified by lpFile. The file should be a document file. If the file is an executable file, the function opens the file, as if "open" had been specified.
"Explore" The function explores the folder specified by lpFile.
  "Play" For methods supporting a play function, such as sound files.
"Properties" For displaying the Properties page for files
0& lpOperation can be also be NULL (0& if declared As Any, or vbNullString if declared As String). In these cases the call performs the default verb action on the file specified, which is usually Open.  The default action can be seen by viewing specific extension in Explorer's Tool / Folder Options / File Types.
lpFile A string that specifies the file to open or print or the folder to open or explore. The function can open an executable file or a document file. The function can print a document file.
lpParameters If the lpFile parameter specifies an executable file, lpParameters is a string that specifies the parameters to be passed to the application (the startup parameters). If lpFile specifies a document file, lpParameters should be NULL (0& or vbNullString).
lpDirectory A string that specifies the default (working) directory.
nShowCmd Like other show commands, this specifies how the application is to be shown when it is opened

The demo below uses the ShellExecute API to launch common operations; email, internet explorer sites, opening documents, playing sounds, just a subset of the things you can do with this API.  A single wrapper routine of three lines provides all the functionality. By trapping the return value you can optionally display the "Open With" dialog.

Note that some items in the Command1 code have hard-coded paths to files. If the ShellExecute call appears to do nothing, check to ensure that item's file reference exists. Placing a Me.Caption = Index statement in Option1_Click can be of help.

If you need to obtain information about the application that is launched as a result of calling ShellExecute, use the ShellExecuteEx API instead.

 BAS Module Code
None.

 Form Code
This demo recreates the form above - just add one option button (Option1) and one label (Label1) and set the Index property of each control to 0 to create control arrays. 95% of the code below supports the control creation and variable population for this demo; the actual call is just a few lines (the last procedure in the code).

Add a single command button (Command1) and the following code into the general declarations area of the form:


Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private dwOptSelected As Long

Private Const SW_SHOWNORMAL As Long = 1
Private Const SW_SHOWMAXIMIZED As Long = 3
Private Const SW_SHOWDEFAULT As Long = 10

Private Const mailNewLine = "%0D%0A"

Private Declare Function GetDesktopWindow Lib "user32" () As Long

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()

   Call CreateControls
   Option1(0).Value = True
   
End Sub


Private Sub Form_Unload(Cancel As Integer)

   Dim cnt As Long
   
   For cnt = Option1.UBound To 1 Step -1
      Unload Option1(cnt)
   Next
   
   For cnt = Label1.UBound To 1 Step -1
      Unload Label1(cnt)
   Next
   
End Sub


Private Sub Option1_Click(Index As Integer)

   dwOptSelected = Index
   
End Sub


Private Sub Command1_Click()

   Dim sTopic As String
   Dim sFile As String
   Dim sParams As String
   Dim sDirectory As String

  'set default setting to be used
  'if not specifically required
   sTopic = "Open"
   sFile = vbNullString
   sParams = vbNullString
   sDirectory = vbNullString
              
  'set custom values based on selected item
   With Option1(dwOptSelected)
      Select Case dwOptSelected
      
      '---------------------------------------------
      'Block2 (column 1) - BROWSER DEMOS
         Case 0:  'Open Default Browser
            sFile = "http://www.mvps.org/vbnet/"
            
         Case 1:  'IE Default Home Page (new browser)
            sFile = "explorer.exe"
            sParams = "::{871C5380-42A0-1069-A2EA-08002B30309D}"
         
         Case 2:  'Specific Browser (knowing exe path)
            sFile = "C:\Program Files\Internet Explorer\iexplore.exe"
            sParams = "http://www.mvps.org/vbnet/"

         Case 3:  'Email w/subject/sig
            sFile = "mailto:test@who.com?subject=Email via Shellexecute"
            
      '---------------------------------------------
      'Block2 (column 1) - EMAIL DEMOS
         Case 4:  'Email w/subject/message
            sFile = "mailto:me@mydesk.com?" & _
                    "&subject=" & "Test Message" & _
                    "&body=" & "Test message using the default email client."
                    
         Case 5:  'Email w/cc/bcc/message
            sFile = "mailto:me@mydesk.com" & _
                    "?cc=someone@outhere.com" & _
                    "&bcc=hidden@recipient.com" & _
                    "&subject=" & "Test Message" & _
                    "&body=" & "Test message using the default email client."
         
         Case 6:  'Email w/mutli-line message
               sFile = "mailto:me@mydesk.com?cc=someone@outhere.com" & _
                       "&subject=Test Message" & _
                       "&body=Test using default email client, line 1." & _
                        mailNewLine & "And this is line 2."
         
      '---------------------------------------------
      'Block 3 (column 1) - NEWS DEMOS
         Case 7:  'msnews w/default news reader
            sFile = "news://msnews.microsoft.com/"
   
         Case 8:  'msnews - specific acct (vb.winapi)
            sFile = "news://msnews.microsoft.com/microsoft.public.vb.winapi"

      '---------------------------------------------
      'Block 4 (column 1) - FILE SYSTEM DEMOS
         Case 9:  '.doc Files (Association)
            sFile = "c:\my documents\somefile.doc"
            
         Case 10:  '.txt Files (Association)
            sFile = "c:\my documents\somefile.txt"
         
         Case 11:  '.wav Files (Open)
            sFile = "c:\windows\media\notify.wav"
            
         Case 12:  '.wav Files (Play)
            sTopic = "Play"
            sFile = "c:\windows\media\notify.wav"
            
         Case 13:  '.avi (Play)
            sTopic = "Play"
            sFile = "d:\graphics\vbgfx\anis\glassie box.ani"
         
         Case 14:  '.bat (for exiting in notepad)
            sFile = "c:\windows\notepad.exe"
            sParams = "c:\autoexec.bat"
            
         Case 15:  '.lnk Files (Open shortcut)
            sFile = "c:\documents and settings\birchr\desktop\agent ransack.lnk"
            
         Case 16:  '.html (Open local HTML File)
            sFile = "c:\web files\index.html"

      '---------------------------------------------
      'Block 1 (column 2) - EXPLORER (absolute)
         Case 18:  'Rooted @ program files (default view)
            sFile = "explorer.exe"
            sParams = "/root,c:\program files"
               
         Case 19:  'Rooted @ program files (explorer view)
            sFile = "explorer.exe"
            sParams = "/e,/root,c:\program files"
         
         Case 20:  'My Computer, specific folder opened
            sFile = "explorer.exe"
            sParams = "/e,c:\program files"
         
         Case 21:  'Explore Drive C:\
            sFile = "explorer.exe"
            sParams = "/e,c:\"
         
         Case 22:  'Explore Current Drive (same as CurDrive)
            sFile = "explorer.exe"
            sParams = "/e,\"
            
         Case 23:  'Recycle Bin
            sFile = "explorer.exe"
            sParams = "/n,::{645FF040-5081-101B-9F08-00AA002F954E}"
         
         Case 24:  'Open folder & select file (default view)
            sFile = "explorer.exe"
            sParams = "/select,c:\windows\notepad.exe"
            
         Case 25:  'Explore folder && select file
            sFile = "explorer.exe"
            sParams = "/e,/select,c:\windows\notepad.exe"
            
         Case 26:  'Root at specific folder (default view)
            sFile = "explorer.exe"
            sParams = "/root,c:\windows"
            
         Case 27:  'Root at specific folder (default view)
            sFile = "c:\windows\"
            sTopic = "Find"
                        
      '---------------------------------------------
      'Block 2 (column 2) - EXPLORER (localized)
         Case 28:  'My Computer (default view)
            sFile = "explorer.exe"
            sParams = "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
            
         Case 29:  'My Computer (explorer view)
            sFile = "explorer.exe"
            sParams = "/e,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
         
         Case 30:  'My Documents (default view)
            sFile = "explorer.exe"
            sParams = "::{450D8FBA-AD25-11D0-98A8-0800361B1103}"
         
         Case 31:  'My Documents (explorer view)
            sFile = "explorer.exe"
            sParams = "/e,::{450D8FBA-AD25-11D0-98A8-0800361B1103}"
         
         Case 32:  'My Documents (rooted)
            sFile = "explorer.exe"
            sParams = "/root,::{450D8FBA-AD25-11D0-98A8-0800361B1103}"
         
         Case 33:  'My Network Places (default view)
            sFile = "explorer.exe"
            sParams = "::{208D2C60-3AEA-1069-A2D7-08002B30309D}"
                        
         Case 34:  'Network Connections (default view)
            sFile = "explorer.exe"
            sParams = "::{7007ACC7-3202-11D1-AAD2-00805FC1270E}"
            
         Case 35:  'Network Connections (explorer view)
            sFile = "explorer.exe"
            sParams = "/e,::{7007ACC7-3202-11D1-AAD2-00805FC1270E}"
         
         Case 36:  'Printers & Faxes (default view)
            sFile = "explorer.exe"
            sParams = "::{2227A280-3AEA-1069-A2DE-08002B30309D}"
            
         Case 37:  'Printers & Faxes (explorer view)
            sFile = "explorer.exe"
            sParams = "/e,::{2227A280-3AEA-1069-A2DE-08002B30309D}"
            
         Case 38:  'Search results (files, default view)
            sFile = "explorer.exe"
            sParams = "::{e17d4fc0-5564-11d1-83f2-00a0c90dc849}"
         
         Case 39:  'Search results (computers, default view)
            sFile = "explorer.exe"
            sParams = "::{1f4de370-d627-11d1-ba4f-00a0c91eedba}"
         
         Case 40:  'Scheduled Tasks (default view)
            sFile = "explorer.exe"
            sParams = "::{D6277990-4C6A-11CF-8D87-00AA0060F5BF}"
      End Select

   End With
   
   Call RunShellExecute(sTopic, sFile, sParams, sDirectory, SW_SHOWDEFAULT)
   
End Sub


Private Sub CreateControls()

   Dim cnt As Long
   Dim vtmp As Long
   Dim vtmp2 As Long
   Dim vtmp3 As Long
         
  'Block 1 (column 1) - BROWSER DEMOS
   With Label1(0)
      .AutoSize = True
      .ForeColor = &HDD3300
      .Move 200, 200
      .Caption = "Browser:"
      .Visible = True
   End With
   
   For cnt = 0 To 2
      If cnt > 0 Then Load Option1(cnt)
      With Option1(cnt)
         .Height = 255
         .Move 1330, 130 + (cnt * .Height), 3200
         .Visible = True
         vtmp = .Top + .Height
      End With
   Next cnt
   
   vtmp2 = vtmp

  'Block 2 (column 1) - EMAIL DEMOS
   Load Label1(1)
   With Label1(1)
      .AutoSize = True
      .Move 200, vtmp + 200
      .Caption = "Email && News:"
      .Visible = True
   End With
   
   For cnt = 3 To 6
      Load Option1(cnt)
      With Option1(cnt)
         .Height = 255
         .Move 1330, vtmp2 + 160 + ((cnt - 3) * .Height), 3200
         .Visible = True
         vtmp = .Top + .Height
      End With
   Next cnt
   
   vtmp2 = vtmp
   
  'Block 3 (column 1) - NEWS DEMOS
   Load Label1(2)
   With Label1(2)
      .AutoSize = True
      .Move 200, vtmp + 200
      .Caption = "News:"
      .Visible = True
   End With
   
   For cnt = 7 To 8
      If cnt > 0 Then Load Option1(cnt)
      With Option1(cnt)
         .Height = 255
         .Move 1330, vtmp2 + 160 + ((cnt - 7) * .Height), 3200
         .Visible = True
         vtmp = .Top + .Height
      End With
   Next cnt
   
   vtmp2 = vtmp

  'Block 4 (column 1) - FILE SYSTEM DEMOS
   Load Label1(3)
   With Label1(3)
      .AutoSize = True
      .Move 200, vtmp + 200
      .Caption = "File System:"
      .Visible = True
   End With

   For cnt = 9 To 17
      Load Option1(cnt)
      With Option1(cnt)
         .Height = 255
         .Move 1330, vtmp2 + 160 + ((cnt - 9) * .Height), 3200
         .Visible = True
         vtmp = .Top + .Height
      End With
   Next cnt

   vtmp3 = vtmp 'to position the command button later
   vtmp = -30   'reset
   vtmp2 = vtmp 'vtmp increments, we need another copy
   
  'Block 1 (column 2) - EXPLORER (absolute)
   Load Label1(4)
   With Label1(4)
      .AutoSize = True
      .Move 4600, 200
      .Caption = "Explorer (absolute):"
      .Visible = True
   End With

   For cnt = 18 To 27
      Load Option1(cnt)
      With Option1(cnt)
         .Height = 255
         .Move 6150, vtmp2 + 160 + ((cnt - 18) * .Height), 3200
         .Visible = True
         vtmp = .Top + .Height
      End With
   Next cnt

   vtmp2 = vtmp

  'Block 2 (column 2) - EXPLORER (localized)
   Load Label1(5)
   With Label1(5)
      .AutoSize = True
      .Move 4600, vtmp + 200
      .Caption = "Explorer (localized):"
      .Visible = True
   End With

   For cnt = 28 To 40
      Load Option1(cnt)
      With Option1(cnt)
         .Height = 255
         .Move 6150, vtmp2 + 160 + ((cnt - 28) * .Height), 3200
         .Visible = True
         vtmp = .Top + .Height + 120
      End With
   Next cnt
      
   With Command1
      .Caption = "Perform action"
      .Move 1330, vtmp3 + 250, 2400
   End With
   
  'throw on the captions
   For cnt = Option1.LBound To Option1.UBound
      With Option1(cnt)
         Select Case cnt
            Case 0: .Caption = "Open Default Browser"
            Case 1: .Caption = "IE Default Home Page (new browser)"
            Case 2: .Caption = "Specific Browser (knowing exe path)"

            Case 3: .Caption = "Email w/subject/sig"
            Case 4: .Caption = "Email w/subject/message"
            Case 5: .Caption = "Email w/cc/bcc/message"
            Case 6: .Caption = "Email w/mutli-line message"
            Case 7: .Caption = "msnews w/default news reader"
            Case 8: .Caption = "msnews - specific acct (vb.winapi)"
            
            Case 9: .Caption = ".doc Files (Association)"
            Case 10: .Caption = ".txt Files (Association)"
            Case 11: .Caption = ".wav Files (Open)"
            Case 12: .Caption = ".wav Files (Play)"
            Case 13: .Caption = ".avi (Play)"
            Case 14: .Caption = ".bat (for exiting in notepad)"
            Case 15: .Caption = ".lnk Files (Open file via shortcut)"
            Case 16: .Caption = ".html (Open local HTML File)"

            Case 18: .Caption = "Rooted @ program files (default view)"
            Case 19: .Caption = "Rooted @ program files (explorer view)"
            Case 20: .Caption = "My Computer, specific folder opened"
            Case 21: .Caption = "Explore Drive C:\"
            Case 22: .Caption = "Explore Current Drive (same as CurDrive)"
            Case 23: .Caption = "Recycle Bin"
            Case 24: .Caption = "Open folder && select file (default view)"
            Case 25: .Caption = "Explore folder && select file"
            Case 26: .Caption = "Root at specific folder (default view)"
            Case 27: .Caption = "Search for files (specifying start point)"

            Case 28: .Caption = "My Computer (default view)"
            Case 29: .Caption = "My Computer (explorer view)"
            Case 30: .Caption = "My Documents (default view)"
            Case 31: .Caption = "My Documents (explorer view)"
            Case 32: .Caption = "My Documents (default view,rooted)"
            Case 33: .Caption = "My Network Places (default view)" 'aka NetworkNeighborhood
            Case 34: .Caption = "Network Connections (default view)"
            Case 35: .Caption = "Network Connections (explorer view)"
            Case 36: .Caption = "Printers && Faxes (default view)"
            Case 37: .Caption = "Printers && Faxes (explorer view)"
            Case 38: .Caption = "Search results (files, default view)"
            Case 39: .Caption = "Search results (computers, default view)"
            Case 40: .Caption = "Scheduled Tasks (default view)"
         End Select
   
      End With
   Next
   
End Sub


Private Sub RunShellExecute(sTopic As String, _
                            sFile As Variant, _
                            sParams As Variant, _
                            sDirectory As Variant, _
                            nShowCmd As Long)

   Dim hWndDesk As Long
   Dim success As Long
  
  'the desktop will be the
  'default for error messages
   hWndDesk = GetDesktopWindow()
  
  'execute the passed operation
   success = ShellExecute(hWndDesk, sTopic, sFile, sParams, sDirectory, nShowCmd)

  'This is optional. Uncomment the three lines
  'below to have the "Open With.." dialog appear
  'when the ShellExecute API call fails
  'If success < 32 Then
  '   Call Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " & sFile, vbNormalFocus)
  'End If
   
End Sub
 Comments

 
 

PayPal Link
Make payments with PayPal - it's fast, free and secure!

 
 
 
 

Copyright ©1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy

 

Hit Counter