activex控件:用VB6.0的ActiveXControl控件实现异步下载

  序:笔者(airon,softWorker)注意到在VB6中要实现文件下载般用和思路方法都是使用第 3方Control控件比如IEControl控件呀winscok呀但在本文中不用添加任何Control控件也不引用任何object就可实现文件下载而且不支持文件下载进度捕获下载激活下载完成事件等

  具体思路方法:

  1.新建VB6工程(默认有个Form1窗体)

  2.选择工程菜单“添加用户Control控件”来添加个用户Control控件

  3.更改Activex用户Control控件名称更改为 Downloader (此项可省)

  4.输入代码:(在用户Control控件代码窗口中)

  Option Explicit
Event DownloadProgress(CurBytes As Long, MaxBytes As Long, SaveFile As String)
Event DownloadError(SaveFile As String)
Event DownloadComplete(MaxBytes As Long, SaveFile As String)
'Public downStat As Boolean
Public Function CancelAsyncRead As Boolean
 On Error Resume Next
 UserControl.CancelAsyncRead
End Function
'Private Sub Timer1_Timer
 ' If Not downStat Then
 ' Timer1.Enabled = False
' Exit Sub
' End If
' Static Cs As Integer
' If Cs > 2 Then Cs = 0
' UserControl.Picture = P1(Cs).Picture
' Cs = Cs + 1
' DoEvents
'End Sub
Private Sub UserControl_AsyncReadComplete(AsyncProp As AsyncProperty)
 On Error Resume Next
 Dim f As Byte, fn As Long
 If AsyncProp.BytesMax <> 0 Then
  fn = FreeFile
  f = AsyncProp.Value
  Open AsyncProp.PropertyName For Binary Access Write As #fn
  Put #fn, , f
  Close #fn
 Else
  RaiseEvent DownloadError(AsyncProp.PropertyName)
 End If
 RaiseEvent DownloadComplete(CLng(AsyncProp.BytesMax), AsyncProp.PropertyName)
 downStat = False
End Sub
Private Sub UserControl_AsyncReadProgress(AsyncProp As AsyncProperty)
 On Error Resume Next
 If AsyncProp.BytesMax <> 0 Then
  RaiseEvent DownloadProgress(CLng(AsyncProp.BytesRead), CLng(AsyncProp.BytesMax),AsyncProp.PropertyName)
  downStat = True: Timer1.Enabled = True
 End If
End Sub
'Private Sub UserControl_Resize
' SizeIt
'End Sub
Public Sub BeginDownload(url As String, SaveFile As String)
 On Error GoTo ErrorBeginDownload
 downStat = True
 UserControl.AsyncRead url, vbAsyncTypeByteArray, SaveFile, vbAsyncReadForceUpdate
 Timer1.Enabled = True
 Exit Sub
ErrorBeginDownload:
 downStat = False
 MsgBox Err & "开始下载数据失败!" _
& vbCrLf & vbCrLf & ":" & Err.Description, vbCritical, ""
End Sub
'Public Sub SizeIt
' _disibledevent=
Private Sub Command1_Click
Downloader1.BeginDownload url, SaveFile
'请把 URL 替代为 Http://文件路径
'请把 savefile 替代为下载到本地文件路径和名称
End Sub
Private Sub Downloader1_DownloadComplete(MaxBytes As Long, SaveFile As String)
MsgBox "文件下载完成保存文件名为:" & SaveFile, vbInformation Or vbOKOnly, "提示:"
End Sub
Private Sub Downloader1_DownloadError(SaveFile As String)
MsgBox "下载发生!", vbExclamation Or vbOKOnly, ":"
End Sub
Private Sub Downloader1_DownloadProgress(CurBytes As Long, MaxBytes As Long, SaveFile As String)
'在这里添加进度第代码
End Sub


Tags:  ieactivex控件 activex控件和插件 安装activex控件 activex控件

延伸阅读

最新评论

发表评论