vb.net - 将事件 arg 发送到自定义事件处理函数
问题描述
我有一个类,它启动一个 webclient 对象并有一个DownloadProgressChanged
和一个DownloadFileCompleted
事件。一个表单可以启动这个对象和下载。如果用户选择关闭表单,表单也可以停止下载。
DownloadFileCompleted
事件处理函数还接受一个参数文件名来引发事件,然后表单类可以处理该事件。我阅读了如何定义此类自定义处理程序函数,因此我的代码如下所示:
AddHandler fileReader.DownloadFileCompleted, Sub(sender, e) download_complete(FileName)
AddHandler fileReader.DownloadProgressChanged, AddressOf Download_ProgressChanged
fileReader.DownloadFileAsync(New Uri(Address), ParentPath + FileName)
Private Sub download_complete(filename As String)
RaiseEvent DownloadDone(filename)
End Sub
我注意到当用户关闭表单时,下载停止但我仍然收到一个下载完成事件(我已经读过这会附带e.Cancelled = True
)
我的问题是我想在引发事件时发送此信息,因此我的download_complete
Sub 会显示如下内容:
Private Sub download_complete(filename As String, e as AsyncCompletedEventArgs)
If e.Cancelled = True Then
RaiseEvent DownloadDone(filename, "CANCELLED")
Else
RaiseEvent DownloadDone(filename, "COMPLETE")
End If
End Sub
这样我就可以在表单的事件处理程序方法中很好地处理以下过程。我找不到该方法的任何文档。有人可以帮我吗?
解决方案
如果我对您的理解正确,这就是您需要做的事情:
Imports System.ComponentModel
Imports System.Net
Public Class Form1
Public Event DownloadComplete As EventHandler(Of DownloadCompleteEventArgs)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim downloader As New WebClient
AddHandler downloader.DownloadFileCompleted, AddressOf downloader_DownloadFileCompleted
Dim sourceUri As New Uri("source address here")
Dim destinationPath = "destination path here"
downloader.DownloadFileAsync(sourceUri, destinationPath, destinationPath)
End Sub
Private Sub downloader_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
Dim downloader = DirectCast(sender, WebClient)
RemoveHandler downloader.DownloadFileCompleted, AddressOf downloader_DownloadFileCompleted
Dim filePath = CStr(e.UserState)
OnDownloadComplete(New DownloadCompleteEventArgs(filePath, e.Cancelled))
End Sub
Protected Overridable Sub OnDownloadComplete(e As DownloadCompleteEventArgs)
RaiseEvent DownloadComplete(Me, e)
End Sub
End Class
Public Class DownloadCompleteEventArgs
Inherits EventArgs
Public ReadOnly Property FilePath As String
Public ReadOnly Property IsCancelled As Boolean
Public Sub New(filePath As String, isCancelled As Boolean)
Me.FilePath = filePath
Me.IsCancelled = isCancelled
End Sub
End Class
您首先调用DownloadFileAsync
允许您传递数据的重载,然后返回DownloadFileCompleted
事件处理程序。然后,在该事件处理程序中,您可以使用我在博客文章中概述的步骤,使用您想要的信息引发您自己的自定义事件。
推荐阅读
- reactjs - 反应js无法读取未定义的属性'id'
- django - Django 3 - 如何从另一个表(外键)动态加载 CBV 中的 CharField 选项?
- dynamics-crm - 在哪里可以找到 CrmJobEditor 源代码?
- sql - 如何从角色中删除所有权限而不在 SQL Server 中重新创建它
- python - 如何在 cython C++ 构建中正确链接到 C 库
- postgresql - 在计算字段的 PostgreSQL 函数中使用 Hasura 会话
- arrays - 基于特定单元格隐藏/显示多个对象
- node.js - 将 node_modules 文件夹移动到不同的位置?
- scikit-learn - 如何在高斯混合模型中限制估计均值?
- javascript - jQuery DataTables:选中页面加载时的所有复选框