VB.net webbrowser 自定义下载接口实现

news/2025/3/20 18:02:58/

 使用《VB.net webbrowser 如何实现自定义下载 IDownloadManager》中的控件ExtendedWebBrowser(下载控件),并扩展了NewWindow2。

使用ExtendedWebBrowser_1过程中,遇到很多问题,花了几天时间,终于解决了所有问题。

问题1:接管了下载后,发现大文件下载,主程序会阻塞。

        一开始,以为是在写文件时因为IO响应导致阻塞,改用异步写,等等...尝试,发现阻塞依然,看过《C# 用FileStream.WriteAsync 异步读文件,调用线程还是被阻塞了》等文章后,问题依然未能解决。

        最后尝试主程序不写文件(就是接管下载后,在OnDataAvailable中对接收数据不操作),不做任何操作,阻塞依然存在。阻塞会导致下载中断,而且这种情况与下载文件大小无关,即使很小几M的文件也会发生。

        苦思中,记起以前写一个延时函数时,为了不阻塞而加入了Application.DoEvents()语句,于是在最频繁操作的OnDataAvailable中加入Application.DoEvents()语句,问题终于得到完满解决。

问题2:写文件

        一开始,是主程序写文件,遇到太多麻烦,在解决问题1中,发现接管了下载后,其实IE是有在后台进程中将文件下载到IE缓冲区的,OnProgress第一次便是返回IE缓冲区中下载的文件名,于是便改用:等下载完后从IE缓冲区复制文件。(貌似IE原有下载器也是这样干的?)

问题3:对于会弹出新窗口的下载,在进行第二次下载时,没有触发下载。

        因为主程序中接管弹出窗口的Extendedwebbrowser_2一直没关闭(IE中下载窗口是立即关闭的),并且发现,在NewWindow2中将弹出下载转到Extendedwebbrowser_2触发下载时,Extendedwebbrowser_2并没有触发DocumentCompleted,估计就是这里导致第二次下载时不能触发。
       解决办法:在下载完后,Extendedwebbrowser_2加载空白页"about:blank",问题解决。
 

下面是IWebBrowserDownloadManager接口完整代码:

Imports Remotion.Dms.Clients.Windows.WebBrowserControl
Imports System.IONamespace MyDownloadmanager                         '定义接口,以实现接口引用 2023.10.27Public Class MyDownloadmanagerImplements IWebBrowserDownloadManagerDim INetCacheFile As String'一些状态的判定(True、False),其中的一种状态(True或False)必须放在接口内进行设定,'不能全部都靠通过外部进程来设定,外部进程只进行其中一种状态的改变就好,否则因为轮询时间差而导致不同步引发非预期结果发生。'例如:AfterLoadBlank#Region "增加属性,将接口的数据传递出去以及传进来"#Region "可读写属性"Private _ContinueDownload As Boolean = TruePublic Property ContinueDownload() As BooleanGetReturn _ContinueDownloadEnd GetSet(ByVal value As Boolean)_ContinueDownload = valueEnd SetEnd PropertyPrivate _DownloadDir As String = ""Public Property DownloadDir() As StringGetReturn _DownloadDirEnd GetSet(ByVal value As String)_DownloadDir = valueEnd SetEnd PropertyPrivate _AttchmentFilename As String = ""Public Property AttchmentFilename() As StringGetReturn _AttchmentFilenameEnd GetSet(ByVal value As String)_AttchmentFilename = valueEnd SetEnd Property'对于会弹出新窗口的下载,因为程序中接管的webbrowser一直没关闭,’在下载完后,需要加载一次新页(在这里加载空白页"about:blank"),‘否则可能无法进行下一次下载。Private _AfterLoadBlank As Boolean = FalsePublic Property AfterLoadBlank() As Boolean    GetReturn _AfterLoadBlankEnd GetSet(ByVal value As Boolean)_AfterLoadBlank = valueEnd SetEnd Property#End Region#Region "ReadOnly Property"Dim _DownloadFileName As String = ""Public ReadOnly Property DownloadFileName() As StringGetReturn _DownloadFileNameEnd GetEnd PropertyPrivate _totalSize As IntegerPublic ReadOnly Property GetTotalSize() As IntegerGetReturn _totalSizeEnd GetEnd PropertyPrivate _currentValue As IntegerPublic ReadOnly Property GetCurrentValue() As IntegerGetReturn _currentValueEnd GetEnd PropertyPrivate _success As BooleanPublic ReadOnly Property GetSuccess() As BooleanGetReturn _successEnd GetEnd PropertyPrivate _statusText As StringPublic ReadOnly Property GetStatusText() As StringGetReturn _statusTextEnd GetEnd PropertyPrivate _isAborted As BooleanPublic ReadOnly Property GetisAborted() As BooleanGetReturn _isAbortedEnd GetEnd PropertyPrivate _IsDownloadCompleted As Boolean = False'下载开始时,设置为false,下载结束或退出时,设置为TruePublic ReadOnly Property IsDownloadCompleted() As Boolean    GetReturn _IsDownloadCompletedEnd GetEnd PropertyPrivate _OnStartDownloading As Boolean = False'下载开始时,设置为false,下载结束或退出时,设置为TruePublic ReadOnly Property OnStartDownloading() As Boolean    GetReturn _OnStartDownloadingEnd GetEnd Property#End Region#End Region#Region "接口函数"Public Sub OnAborted() Implements Remotion.Dms.Clients.Windows.WebBrowserControl.IWebBrowserDownloadManager.OnAbortedWriteRunLog("OnAborted")_isAborted = True_IsDownloadCompleted = True_OnStartDownloading = FalseEnd SubPublic Function OnDataAvailable(ByVal buffer() As Byte, ByVal bytesAvailable As Integer) As Boolean Implements Remotion.Dms.Clients.Windows.WebBrowserControl.IWebBrowserDownloadManager.OnDataAvailable_currentValue += bytesAvailable'需要加这行,否则可能下载时发生阻塞,导致下载中断,而且这种情况与下载文件大小无关,即使很小几M的文件也会发生。Application.DoEvents()      Return _ContinueDownloadEnd Function'在下载完后,需要加载一次新页(在这里加载空白页"about:blank"),否则可能无法进行下一次下载。Public Sub OnDownloadCompleted(ByVal success As Boolean, ByVal statusText As String) Implements Remotion.Dms.Clients.Windows.WebBrowserControl.IWebBrowserDownloadManager.OnDownloadCompleted_isAborted = False_IsDownloadCompleted = True_OnStartDownloading = False_AfterLoadBlank = True_success = success_statusText = statusText_AttchmentFilename = ""WriteRunLog("OnDownloadCompleted:" + success.ToString + "      " + statusText)If success ThenIf String.IsNullOrEmpty(INetCacheFile) ThenWriteRunLog("没有找到IE缓冲区文件!文件 " + _DownloadFileName + " 下载失败!")ElseFile.Copy(INetCacheFile, _DownloadFileName, overwrite:=True)      '从IE缓冲区复制文件WriteRunLog("找到IE缓冲区文件: " + INetCacheFile + ",复制到:" + _DownloadFileName)End IfEnd IfEnd SubPublic Function OnProgress(ByVal currentValue As Integer, ByVal totalSize As Integer, ByVal statusText As String) As Boolean Implements Remotion.Dms.Clients.Windows.WebBrowserControl.IWebBrowserDownloadManager.OnProgress_totalSize = totalSize'从第一次OnProgress中获取下载文件名If String.IsNullOrEmpty(_DownloadFileName) Then      _DownloadFileName = MyGetFileName(statusText)If String.IsNullOrEmpty(_DownloadFileName) Then_DownloadFileName = "TmpFile"End IfIf Directory.Exists(_DownloadDir) Then_DownloadFileName = _DownloadDir + "\" + _DownloadFileNameEnd IfEnd IfIf String.IsNullOrEmpty(INetCacheFile) ThenIf InStr(statusText, "Windows\INetCache") > 0 Then  '查找IE缓冲区文件 保存路径、文件名INetCacheFile = statusText'WriteRunLog("OnProgress找到IE缓冲区文件: " + INetCacheFile)End IfEnd IfSystem.Windows.Forms.Application.DoEvents()Return _ContinueDownloadEnd FunctionPublic Function OnStartDownload(ByVal uri As System.Uri) As Boolean Implements Remotion.Dms.Clients.Windows.WebBrowserControl.IWebBrowserDownloadManager.OnStartDownload_currentValue = 0_OnStartDownloading = True_ContinueDownload = True_IsDownloadCompleted = FalseINetCacheFile = ""_DownloadFileName = ""WriteRunLog("OnStartDownload :" + uri.ToString)Return TrueEnd Function'OnStartDownload:http://115.1.115.15:9080/FrntMonitor/servlet/com.icbc.cte.cs.servlet.CSReqServlet'1、第一次获得文件名   OnProgress:0 totalSize:0 statusText: C:\Users\gdzs-liyh\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\0F2VEW6C\statatmdev[2].xls'2、第二次获得下载链接 OnProgress:3483 totalSize:0 statusText:(OnStartDownload中的网址:http://115.1.115.15:9080/FrntMonitor/servlet/com.icbc.cte.cs.servlet.CSReqServlet)'3483就是在这时候读取的数据大小。'OnProgress:3483 totalSize:0 statusText: C:\Users\gdzs-liyh\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\0F2VEW6C\statatmdev[2].xls'OnDataAvailable:38281  (这个就是文件的实际大小)(可能文件小,此时文件已经下载到缓存:C:\Users\gdzs-liyh\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\0F2VEW6C\statatmdev[2].xls)'OnProgress:38281 totalSize:0 statusText:(OnStartDownload中的网址)'OnDownloadCompleted'================================='OnStartDownload :http://115.96.14.11/kjbbs/UpLoadFile/2010-7/20107214401523292.doc'1、第一次获得文件名   OnProgress:0 totalSize:0 statusText :http://115.96.14.11/kjbbs/UpLoadFile/2010-7/20107214401523292.doc'2、第二次获得下载链接 OnProgress:119296 totalSize:119296 statusText :http://115.96.14.11/kjbbs/UpLoadFile/2010-7/20107214401523292.doc'OnProgress:119296 totalSize:119296 statusText :C:\Users\gdzs-liyh\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\5Q44G40U\20107214401523292.doc'OnProgress:119296 totalSize:119296 statusText :http://115.96.14.11/kjbbs/UpLoadFile/2010-7/20107214401523292.doc'OnDataAvailable:119296  (可能文件小,此时文件已经下载到缓存:C:\Users\gdzs-liyh\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\0F2VEW6C\statatmdev[2].xls)'OnDownloadCompleted#End RegionShared Sub WriteRunLog(ByVal MyMsg As String)'Using w As StreamWriter = File.AppendText("RunLog.txt")Dim w As StreamWriterIf File.Exists("RunLog.txt") ThenIf My.Computer.FileSystem.GetFileInfo("RunLog.txt").Length > 10485760 Then  '2017.5.4 文件大于10M,清0w = File.CreateText("RunLog.txt")w.Write("文件大于10M,置0从头开始!")w.Write(Chr(9))Elsew = File.AppendText("RunLog.txt")End IfElsew = File.CreateText("RunLog.txt")End Ifw.Write(Now)w.Write(Chr(9))     '插入Tab键w.WriteLine(MyMsg)w.Flush()w.Close()'End UsingEnd SubPublic Function MyGetFileName(ByVal inStr As String) As String'获取文件名, '文件夹名、文件名不能包含下列字符\/:*?"<>|Dim ss As Stringss = System.IO.Path.GetFileName(inStr)Dim n = InStrRev(ss, "=")If n < ss.Length Thenss = ss.Substring(n)End IfMyGetFileName = ss.Replace("\", "").Replace("/", "").Replace(":", "").Replace("*", "").Replace("?", "").Replace(Chr(34), "").Replace("<", "").Replace(">", "").Replace("|", "")If InStrRev(MyGetFileName, "[") > 1 And InStrRev(MyGetFileName, "[") < InStrRev(MyGetFileName, "]") Then    '将 21018102002617385797[1] 中的 [1] 去掉MyGetFileName = Left(MyGetFileName, InStrRev(MyGetFileName, "[") - 1) + Mid(MyGetFileName, InStrRev(MyGetFileName, "]") + 1)End IfMyGetFileName = _AttchmentFilename + MyGetFileNameEnd FunctionEnd ClassEnd Namespace

文章来源:https://blog.csdn.net/zslefour/article/details/134439084
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ppmy.cn/news/1223601.html

相关文章

竞赛 题目:基于LSTM的预测算法 - 股票预测 天气预测 房价预测

文章目录 0 简介1 基于 Keras 用 LSTM 网络做时间序列预测2 长短记忆网络3 LSTM 网络结构和原理3.1 LSTM核心思想3.2 遗忘门3.3 输入门3.4 输出门 4 基于LSTM的天气预测4.1 数据集4.2 预测示例 5 基于LSTM的股票价格预测5.1 数据集5.2 实现代码 6 lstm 预测航空旅客数目数据集预…

【部署篇】Docker配置MySQL容器+远程连接

一、前言 上篇文章在部署nestjs时&#xff0c;由于docker访问不了主机的localhost&#xff0c;所以无法连接主机数据库。所以我们只能在docker中额外配置一个数据库&#xff0c;映射到主机上&#xff0c;然后可以通过ip地址访问。 在本篇文章我们会在docker中创建一个mysql&a…

【SpringMvc】SpringMvc +MyBatis整理

&#x1f384;欢迎来到边境矢梦的csdn博文&#x1f384; &#x1f384;本文主要梳理 Java 框架 中 SpringMVC的知识点和值得注意的地方 &#x1f384; &#x1f308;我是边境矢梦&#xff0c;一个正在为秋招和算法竞赛做准备的学生&#x1f308; &#x1f386;喜欢的朋友可以关…

数组——C语言初阶

一.一维数组&#xff1a; &#xff08;1&#xff09;.一维数组的创建 概念&#xff1a; type_t arr_name [const_n]; //type_t 是指数组的元素类型 //arr_name 是数组的名字 //const_n 是一个常量表达式&#xff0c;用来指定数组的大小数组创建实例&#xff1a; #include…

深度图生成3D点云

从立体相机到 3D 传感器的许多设备都可以深度图的形式提供有关它们正在捕获的场景的距离信息。 为了从此类图像中获取有意义的数据&#xff0c;通常需要将这些深度图转换为 3D 点云。 在这篇文章中&#xff0c;我们将使用 Microsoft Kinect V2 获得的深度帧执行此类转换&#…

一阶滤波器(一阶巴特沃斯滤波器)

连续传递函数G(s) 离散传递函数G(z) 转换为差分方程形式 一阶巴特沃斯滤波器Filter Designer参数设计&#xff1a;参考之前的博客Matlab的Filter Designer工具设计二阶低通滤波器 设计采样频率100Hz&#xff0c;截止频率20Hz。 注意&#xff1a;设计参数使用在离散系统中&…

springMvc中的拦截器【巩固】

先实现下想要的拦截器功能 package com.hmdp.utils;import com.hmdp.entity.User; import org.springframework.web.servlet.HandlerInterceptor;import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Ht…

ArmV8常用汇编指令

1.syntax用法 GNU汇编器的.syntax .syntax命令是ARM架构独有的命令&#xff0c;语法为 .syntax [unified | divided]&#xff1b;作用是在汇编ARM指令时&#xff0c;指定按照什么样的语法规则进行汇编。如果在编写汇编语言时不使用该命令指定语法规则&#xff0c;那么默认采用.…