Copy files with progress bar

2020-06-28 10:50发布

问题:

So I am trying to do something in visual basic I start learning but still that is not enough. Mostly I am using codes from internet. Now I want to copy few files from first folder to second folder and overwrite existing files and I want to see progress on progress bar (all files together are about 2GB)

SOLVED: I found source code for some program and used some parts to make this work

回答1:

Here is my favorite way of doing it... Using the SHFileOperation API

This API will automatically show the progress as shown in the screenshot below.

Here is an example. Paste this code in a module

Public Declare Function SHFileOperation Lib "shell32.dll" _
Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As Long

Public Const FO_COPY = &H2
Public Const FOF_SIMPLEPROGRESS = &H100

Public Type SHFILEOPSTRUCT
    hWnd As Long
    wFunc As Long
    pFrom As String
    pTo As String
    fFlags As Integer
    fAnyOperationsAborted As Long
    hNameMappings As Long
    lpszProgressTitle As Long
End Type

Public Sub VBCopyFolder(ByRef strSource As String, ByRef strTarget As String)
    Dim op As SHFILEOPSTRUCT

    With op
        .wFunc = FO_COPY
        .pTo = strTarget
        .pFrom = strSource
        .fFlags = FOF_SIMPLEPROGRESS
    End With

    '~~> Perform operation
    SHFileOperation op
End Sub

and then copy files or folders like this

Private Sub Sample()
    '~~> Copy Files
    Call VBCopyFolder("C:\Sample.Avi", "C:\NewSample.Avi")

    '~~> Copy Folders
    Call VBCopyFolder("C:\Temp1", "C:\Temp2")
End Sub

Screenshot