在使用Webbrowser抓取网页信息时,碰到需要下载文件,这时需要用户介入操作,如何避免:
首先引进
[DllImport("urlmon.dll", CharSet = CharSet.Auto, SetLastError = true)] static extern Int32 URLDownloadToFile( [MarshalAs(UnmanagedType.IUnknown)] object pCaller, [MarshalAs(UnmanagedType.LPWStr)] string szURL, [MarshalAs(UnmanagedType.LPWStr)] string szFileName, Int32 dwReserved, IntPtr lpfnCB);
再添加
this.WebBrowser.Navigating += WebBrowser_Navigating;
void WebBrowser_Navigating(object sender, WebBrowserNavigatingEventArgs e){ //设置下载条件 if (e.Url != null && e.Url.AbsolutePath.IndexOf("/V1/Delivery/Download") > -1) { try { if (Citation.IsValid) { UIManager.ProgressMessageHandler(this, new UIEventArgs { Message = "Downloading "+ e.Url.Segments[e.Url.Segments.Length - 1]}); string fullname = Path.Combine(pdfSavePath_, e.Url.Segments[e.Url.Segments.Length - 1]); //在这替换“下载提示框”,并自定义下载 int response = URLDownloadToFile(null, e.Url.AbsoluteUri, fullname, 0, IntPtr.Zero); if (response == 0) { Citation.IsDownloaded = true; UIManager.ProgressMessageHandler(this, new UIEventArgs { Message = Citation.Name + " has downloaded." }); } } } catch { } finally { //取消“下载提示框”,不会再提示用户 e.Cancel = true; } } }