
How-To... - Launch Files with their Associated Applications through Visual Basic
When
using the Shell function through Visual Basic, if you wish to launch, for
example, a .DOC file. You would expect it to open up and load into Wordpad
or Word, but it doesn't. The Shell function can only be used to run EXE, BAT,
COM, etc. To be able to launch other files such as DOC, or TXT, you have to
use the ShellExecute API call. The call is as follows :-
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
On the form, insert 4 buttons -- cmdDoc, cmdTxt, cmdHtml and cmdVbp. The syntax to load a file into its associated application is as follows :-
ret = ShellExecute(Me.hwnd, vbNullString,
filename, vbNullString, directory, 1)
Filename is the name of the file that is going to be launched. Directory is the location of the file(includes drive and path). Now, in the General Declarations part of the form, insert the following code :-
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 cmdDoc_Click()
Dim ret As Long
ret = ShellExecute(Me.hwnd, vbNullString, "vbhowto.doc", vbNullString, CurDir,
1)
End Sub
Private Sub cmdHtml_Click()
Dim ret As Long
ret = ShellExecute(Me.hwnd, vbNullString, "readme.htm", vbNullString, CurDir,
1)
End Sub
Private Sub cmdTxt_Click()
Dim ret As Long
ret = ShellExecute(Me.hwnd, vbNullString, "vbhowto.txt", vbNullString, CurDir,
1)
End Sub
Private Sub cmdVbp_Click()
Dim ret As Long
ret = ShellExecute(Me.hwnd, vbNullString, "assocapps.vbp", vbNullString, CurDir,
1)
End Sub
'<---END OF CODE--->
Now, run the program. Click on one of the buttons and it will run the file in the associated application.
You can download this example by clicking here