使用API函数复制文件,可显示进度。

  以前一直以为用API函数只能调用系统的那个复制的对话框来显示进度,原来还有其他方法可以用,不过这个API只能在NT4.0及以上的版本上面才有。
  在工程里添加一个模块,将以下代码复制到模块里
Private Const PROGRESS_CANCEL = 1
Private Const PROGRESS_CONTINUE = 0
Private Const PROGRESS_QUIET = 3
Private Const PROGRESS_STOP = 2
Private Const COPY_FILE_FAIL_IF_EXISTS = &H1
Private Const COPY_FILE_RESTARTABLE = &H2

'// 此 API 在 WIN9X 下不能使用
Private Declare Function CopyFileEx Lib "kernel32.dll" Alias "CopyFileExA" (ByVal lpExistingFileName As String, ByVal lpNewFileName As String, ByVal lpProgressRoutine As Long, lpData As Any, ByRef pbCancel As Long, ByVal dwCopyFlags As Long) As Long

Private mlngCancel                  As Long
Private mprgState                   As Object
Private mlblState                   As Object

Public Function CopyProgressRoutine(ByVal TotalFileSize As Currency, _
                                    ByVal TotalBytesTransferred As Currency, _
                                    ByVal StreamSize As Currency, _
                                    ByVal StreamBytesTransferred As Currency, _
                                    ByVal dwStreamNumber As Long, _
                                    ByVal dwCallbackReason As Long, _
                                    ByVal hSourceFile As Long, _
                                    ByVal hDestinationFile As Long, _
                                    ByVal lpData As Long) As Long
   '// 显示进度
   mprgState.Value = CLng((100 / TotalFileSize) * TotalBytesTransferred)
   mlblState.Caption = "已完成: " & FormatPercent(mprgState.Value / 100, 0)
   '
   DoEvents
   '// 继续复制
   CopyProgressRoutine = PROGRESS_CONTINUE
End Function

'************************************************
'** 函数名称:  uCopyFile
'** 函数功能:  复制文件
'** 参数说明:
'**            strFrom              源文件
'**            strTo                目标文件
'**            prgState             进度条控件
'**            lblState             用来显示进度的 Label
'** 函数返回:
'**            Boolean 类型
'**            True                 复制成功
'**            False                复制失败
'** 参考实例:
'**
'**            blnReturn = uCopyFile("c:/test.exe", "d:/test.exe", prgState, lblState)
'************************************************
Public Function uCopyFile(ByVal strFrom As String, _
                          ByVal strTo As String, _
                          ByRef prgState As Object, _
                          ByRef lblState As Object) As Boolean
   Dim lngReturn                   As Long
  
   Set mprgState = prgState
   Set mlblState = lblState
   '// 开始复制
   lngReturn = CopyFileEx(strFrom, strTo, _
                          AddressOf CopyProgressRoutine, ByVal 0&, mlngCancel, COPY_FILE_RESTARTABLE)

   If lngReturn = 0 Then
      uCopyFile = False
   Else
      uCopyFile = True
   End If
End Function

  在调用时,直接使用 uCopyFile("c:/test.exe", "d:/test.exe", prgState, lblState),其中的 prgState 你可以去掉不要,由自己来定。

你可能感兴趣的:(编程相关,api,function,object,string,file,c)