Visual Basic Programming Code Examples
Visual Basic > Files Directories Drives Code Examples
Copy files using the File Copy Shell
Copy files using the File Copy Shell
To perform "Explorer" type file coping (including the "file copy" dialog) use the following routine:
Option Explicit
Private Type SHFILEOPSTRUCT
hWnd As Long
wFunc As Long
pFrom As String
pTo As String
fFlags As Integer
fAnyOperationsAborted As Boolean
hNameMappings As Long
lpszProgressTitle As String
End Type
Private Type BrowseInfo
hWndOwner As Long
pidlRoot As Long
sDisplayName As String
sTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
Private Declare Function SHFileOperation Lib "Shell32.dll" Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long
Private Declare Function SHBrowseForFolder Lib "Shell32.dll" (bBrowse As BrowseInfo) As Long
Private Declare Function SHGetPathFromIDList Lib "Shell32.dll" (ByVal lItem As Long, ByVal sDir As String) As Long
'Purpose : Copies file/s from a source path to a destination
'Inputs : sSourceFiles A comma delimited list of files eg "C:\test.txt,C:\other.txt"
'Outputs : Returns 0 on success, else returns an error number
'Notes :
'Revisions :
Public Function FileCopyShell(ByVal sSourceFiles As String, ByVal sDestination As String) As Long
Dim tFileOp As SHFILEOPSTRUCT, lPosComma As Long
Const FO_COPY = &H2, FOF_ALLOWUNDO = &H40
'Replace the commas which Nulls
lPosComma = InStr(1, sSourceFiles, ",")
Do While lPosComma
Mid$(sSourceFiles, lPosComma, 1) = vbNullChar
lPosComma = InStr(lPosComma, sSourceFiles, ",")
Loop
'Initialise the structure
With tFileOp
.hWnd = 0
.wFunc = FO_COPY
.pFrom = sSourceFiles & vbNullChar & vbNullChar
.pTo = sDestination & vbNullChar & vbNullChar
.fFlags = FOF_ALLOWUNDO
End With
FileCopyShell = SHFileOperation(tFileOp)
End Function