Visual Basic Programming Code Examples
Visual Basic > API and Miscellaneous Code Examples
Launch a PC's default browser with ShellExecute API
Launch a PC's default browser with ShellExecute API
Often, you may want a user to access a specific URL on the Web by launching his default browser and navigating to the Web site of your choice. Fortunately, a simple Windows API function ShellExecute() lets you do this. When you pass this function a filename, it uses the Windows file associations to start the appropriate application. As a result, all you need do is pass this function a URL, and it automatically launches the default browser and navigates to the requested location. Below is an example of how to use this API call:
Option Explicit
Private Declare Function GetActiveWindow 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
Public Const SW_SHOWNORMAL = 1
Public Const SW_SHOWMAXIMIZED = 3
Public Const SW_SHOWMINIMIZED = 2
Public Const SW_SHOWDEFAULT = 10
Public Const SW_SHOWNOACTIVATE = 4
Public Const SW_HIDE = 0
'Purpose : Opens a URL using the default browser of the local machine
' [lShow] The window activation setting, defaults to a normal window.
'Outputs : Returns True if successfully executed sURL, else returns False.
Function BrowserOpen(sURL As String, Optional lShow As Long = SW_SHOWNORMAL) As Boolean
Dim lRet As Long
lRet = ShellExecute(GetActiveWindow, vbNullString, sURL, vbNullString, vbNullString, lShow)
If lRet > 32 Then
'Successfully executed the sURL string
BrowserOpen = True
Else
'Failed to open sURL
BrowserOpen = False
Debug.Print "Error Number: " & Err.LastDllError
End If
End Function
Sub Test()
If BrowserOpen("www.example", SW_SHOWNORMAL) Then
MsgBox "Opened www.example"
Else
MsgBox "Failed to open www.example"
End If
End Sub