Wednesday, August 12, 2009

[vb6] Open Any Type Of File With Its Associated Window's Program

You simply want to be able to press a command button, which will trigger a file (e.g. "c:\media\mysong.mp3"), to be opened with by its associated application (e.g. "Media Player") just as what would happen if I went to the file in windows explorer, and double clicked it.

1. Create module modTools as following:
Attribute VB_Name = "modTools"
'*******************************************************************************
' Name : modTools
' Author : Chandra Gunawan
' Date : 22-Jul-2009
' Description : Tools Library
'
' Maintenance Log
' ==============================================================================
' Date ID Description
' ------------------------------------------------------------------------------
'*******************************************************************************

Option Explicit

'==============================================================================
' CONSTANTS & VARIABLES DEFINITION
'==============================================================================
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 Const SW_SHOWNORMAL = 1

'------------------------------------------------------------------------------
' Name : OpenFile
' Author : Chandra Gunawan
' Date : 13-Aug-2009
' Description : Open any type of file with its associated window's program
'------------------------------------------------------------------------------
Public Function OpenFile(ByVal pForm As Form, ByVal pFilePath$) As Long

OpenFile = ShellExecute(pForm.hwnd, "open", pFilePath, vbNullString, vbNullString, SW_SHOWNORMAL)
End Function 'OpenFile

2. Execute OpenFile function inside your button's click-event
Private Sub Command1_Click()
Call OpenFile(Me, "c:\media\mysong.mp3")
End Sub

No comments:

Post a Comment