Open a file/url with its default program

A common VB question is how to open a file (ie a Word document) with its default application when you don't know where the application is installed? The answer is... the same way Explorer does, using the ShellExecute API function. This also lets you open a web address (starting with http://) or an email address (starting with mailto:). The code below gives you an example

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

'// open file (quotes are used so that the actual value that is passed is "C:\test.doc"
Private Sub cmdOpen_Click()
    ShellExecute 0, vbNullString, """"C:\test.doc"""", vbNullString, vbNullString, vbNormalFocus
End Sub

'// open url
Private Sub cmdOpen_Click()
    ShellExecute 0, vbNullString, "http://www.vbweb.co.uk/", vbNullString, vbNullString, vbNormalFocus
End Sub

'// open email address
Private Sub cmdOpen_Click()
    ShellExecute 0, vbNullString, "mailto:support@vbweb.co.uk", vbNullString, vbNullString, vbNormalFocus
End Sub

You might also like...

Comments

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Java is to JavaScript what Car is to Carpet.” - Chris Heilmann