I want to check the downloadHandler in cefsharp chromiumbrowser. My goal is to pause and resume any download. For this, I tried callback.pause ()
and callback.resume ()
commands in downloadHandler.
But I encountered some problems, how can I solve them?
Problem:
- But in my code, when I use the command of
callback.pause()
, process ofOnDownloadUpdated
closes and command ofcallback.resume()
does not work. After giving the command callback.pause(), I should be able to give the command callback.resume() and continue the download from where it left off.
Video: https://youtu.be/3A_HHrEJfTM
Working principle:
When the
OnBeforeDownload
operation runs, thedownloadItem
" panel, which provides download information and control, is added by the"DownloadMenuItemADD()
"function in the "mainForm".In the function "OnDownloadUpdated", the information in the "downloadItem" panel, which provides download information and control, is updated with the function "SETDownloadMenuItemADD".
Thanks to "boolean pause and resume" in "DownloadHandler.cs", "callback.pause() and callback.resume()" transactions are performed.
Screenshots
3)callback.resume() does not work
Code All of DownloadHandler.cs [EDIT]
using CefSharp;
using System;
using System.Windows.Forms;
namespace gencayWeb
{
public class DownloadHandler : IDownloadHandler
{
public event EventHandler<DownloadItem> OnBeforeDownloadFired;
public event EventHandler<DownloadItem> OnDownloadUpdatedFired;
Form1 mainForm;
public DownloadHandler(Form1 form)
{
mainForm = form;
}
public bool pause = false;
public bool resume = false;
public string temp="0"; //NEW
public string _Status="null";
public string _SuggestedFileName="null";
public void OnBeforeDownload(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IBeforeDownloadCallback callback)
{
_SuggestedFileName = downloadItem.SuggestedFileName;
_Status = "Downloading...";
mainForm.DownloadMenuItemADD( _Status, _SuggestedFileName, downloadItem.OriginalUrl, downloadItem.Url, downloadItem.Id, downloadItem.FullPath, downloadItem.StartTime, HesaplaRececive(downloadItem), HesaplaTotal(downloadItem), downloadItem.PercentComplete, Convert.ToString(ConvertBytesToMegabytes(downloadItem.CurrentSpeed)));
var handler = OnBeforeDownloadFired;
if (handler != null)
{
handler(this, downloadItem);
}
if (!callback.IsDisposed)
{
using (callback)
{
callback.Continue(mainForm.FilePath + "\\" + downloadItem.SuggestedFileName, showDialog: false);
}
}
}
public void OnDownloadUpdated(IWebBrowser chromiumWebBrowser, IBrowser browser, DownloadItem downloadItem, IDownloadItemCallback callback)
{
var handler = OnDownloadUpdatedFired;
if (handler != null)
{
handler(this, downloadItem);
}
if (temp == downloadItem.Id.ToString()) //NEW
{
if (pause)
{
callback.Pause();
pause = false;
//_Status = "Paused...";
mainForm.SETDownloadMenuItemSTATUS("Paused...", downloadItem.Id); //NEW
//mainForm.SETDownloadMenuItemADD("Paused...", downloadItem.Id, HesaplaRececive(downloadItem), downloadItem.PercentComplete, Convert.ToString(ConvertBytesToMegabytes(downloadItem.CurrentSpeed)));
MessageBox.Show("CALLBACK PAUSED:", "In DownloadHandler.cs");
}
if (resume)
{
callback.Resume();
resume = false;
//_Status = "Resumed...";
mainForm.SETDownloadMenuItemSTATUS("Resumed",downloadItem.Id);
//mainForm.SETDownloadMenuItemADD("Resumed...", downloadItem.Id, HesaplaRececive(downloadItem), downloadItem.PercentComplete, Convert.ToString(ConvertBytesToMegabytes(downloadItem.CurrentSpeed)));
MessageBox.Show("CALLBACK RESUMED!", "In DownloadHandler.cs");
}
temp = "0";
}
mainForm.SETDownloadMenuItemADD(downloadItem.Id, HesaplaRececive(downloadItem), downloadItem.PercentComplete, Convert.ToString(ConvertBytesToMegabytes(downloadItem.CurrentSpeed)));
if (downloadItem.IsComplete || downloadItem.IsCancelled)
{
if (downloadItem.IsComplete)
{
//_Status = "Completed.";
mainForm.SETDownloadMenuItemSTATUS("Completed", downloadItem.Id);
// mainForm.SETDownloadMenuItemADD("Completed.", downloadItem.Id, HesaplaRececive(downloadItem), downloadItem.PercentComplete, Convert.ToString(ConvertBytesToMegabytes(downloadItem.CurrentSpeed)));
}
if (downloadItem.IsCancelled)
{
//_Status = "Cancelled.";
mainForm.SETDownloadMenuItemSTATUS("Cancelled", downloadItem.Id);
// mainForm.SETDownloadMenuItemADD("Cancelled.", downloadItem.Id, HesaplaRececive(downloadItem), downloadItem.PercentComplete, Convert.ToString(ConvertBytesToMegabytes(downloadItem.CurrentSpeed)));
}
if (downloadItem.IsComplete && downloadItem.IsCancelled)
{
//_Status = "Complete And Cancelled!, This may generate an error";
mainForm.SETDownloadMenuItemSTATUS("Complete And Cancelled!, This may generate an error", downloadItem.Id);
// mainForm.SETDownloadMenuItemADD("Complete And Cancelled!, This may generate an error...", downloadItem.Id, HesaplaRececive(downloadItem), downloadItem.PercentComplete, Convert.ToString(ConvertBytesToMegabytes(downloadItem.CurrentSpeed)));
}
}
//Converting byte type data
static double ConvertBytesToBayt(long bytes)
{
return bytes;
}
static double ConvertBytesToKilobytes(long bytes)
{
return bytes / 1024f;
}
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
static double ConvertBytesToCigabytes(long bytes)
{
return ((bytes / 1024f) / 1024f) / 1024f;
}
private string HesaplaTotal(DownloadItem downloadItem)
{
long bol = 1;
int turno = 0;
string tur = "";
double boyut = 0;
for (bol = 1; downloadItem.TotalBytes >= bol; bol *= 1024)
{
turno++;
}
switch (turno)
{
case 1:
tur = " Bayt";
boyut = ConvertBytesToBayt(downloadItem.TotalBytes);
break;
case 2:
tur = " KB";
boyut = ConvertBytesToKilobytes(downloadItem.TotalBytes);
break;
case 3:
tur = " MB";
boyut = ConvertBytesToMegabytes(downloadItem.TotalBytes);
break;
case 4:
tur = " GB";
boyut = ConvertBytesToCigabytes(downloadItem.TotalBytes);
break;
}
return boyut + tur;
}
private string HesaplaRececive(DownloadItem downloadItem)
{
long bol = 1;
int turno = 0;
string tur = "";
double boyut = 0;
for (bol = 1; downloadItem.ReceivedBytes >= bol; bol *= 1024)
{
turno++;
}
switch (turno)
{
case 1:
tur = " Bayt";
boyut = ConvertBytesToBayt(downloadItem.ReceivedBytes);
break;
case 2:
tur = " KB";
boyut = ConvertBytesToKilobytes(downloadItem.ReceivedBytes);
break;
case 3:
tur = " MB";
boyut = ConvertBytesToMegabytes(downloadItem.ReceivedBytes);
break;
case 4:
tur = " GB";
boyut = ConvertBytesToCigabytes(downloadItem.ReceivedBytes);
break;
}
return boyut + tur;
}
}
}
Code a Little of Form1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.IO;
namespace gencayWeb
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//...
}
private DownloadHandler downer;
ChromiumWebBrowser browser;
//...
private void browserButton_Click(object sender, EventArgs e)
{
//...
browser = new ChromiumWebBrowser("google.com")
{
Name = "browser" + id,
Dock = DockStyle.None,
Location = new Point(0, 40),
BackColor = Color.White,
Visible = true,
Tag = id,
Anchor = AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Bottom,
};
browser.DownloadHandler = downer;
//...
this.Invoke((MethodInvoker)delegate ()
{
this.Controls.Add(browser);
});
//...
}
//...
public string FilePath = Application.StartupPath + "\\Download";
public string fileName = "";
private void ActiveDownloads_Click(object sender, EventArgs e)
{
if (downloadsMenu.Visible == false)
downloadsMenu.Visible = true;
else
downloadsMenu.Visible = false;
}
public void DownloadMenuItemADD(string Status,string SuggestedFileName, string OriginalUrl, string Url, int Id, string FullPath, DateTime? StartTime, string ReceivedBytes, string TotalBytes, int PercentComplete, string CurrentSpeed)
{
fileName = SuggestedFileName;
// MessageBox.Show("::"+"Status:"+Status+"\nDosya: "+SuggestedFileName+"\nId:"+Id+"\nBoyut:"+TotalBytes,"On before");
activeDownloads.Visible = true;
downloadsMenu.Visible = true;
downloadsMenu.BringToFront();
downloadsMenu.Size = new Size();
Panel downloadItem = new Panel()
{
Name = Id.ToString(),
Dock= DockStyle.Top,
Height=100,
AutoSize = true,
Visible = true,
};
Panel cubukUst = new Panel()
{
Name = "cubukUst",
Dock = DockStyle.Top,
Height = 3,
BackColor = Color.Blue,
};
Panel cubukAlt = new Panel()
{
Name = "cubukAlt",
Dock = DockStyle.Bottom,
Height = 3,
BackColor = Color.Blue,
};
downloadItem.Controls.Add(cubukAlt);
downloadItem.Controls.Add(cubukUst);
Label infoLbl = new Label()
{
Name = "infoLbl",
Location=new Point(3,3),
AutoSize=true,
Text="Name:"+SuggestedFileName+"\nSize:"+TotalBytes,
};
downloadItem.Controls.Add(infoLbl);
Label receivedLbl = new Label()
{
Name = "receivedLbl",
Location = new Point(3, infoLbl.Location.Y + infoLbl.Size.Height+10),
AutoSize = true,
Text = "Received: " + ReceivedBytes +"\nSpeed: "+CurrentSpeed,
};
downloadItem.Controls.Add(receivedLbl);
ProgressBar downlaodProgress = new ProgressBar()
{
Name = "downlaodProgress",
Maximum=100,
Value=PercentComplete,
Width=245,
Location=new Point(3, receivedLbl.Location.Y+ receivedLbl.Size.Height+15),
};
downloadItem.Controls.Add(downlaodProgress);
Label percentLbl = new Label()
{
Name = "percentLbl",
Location = new Point(3, downlaodProgress.Location.Y+downlaodProgress.Height+3),
AutoSize = true,
Text = "% " + PercentComplete,
};
downloadItem.Controls.Add(percentLbl);
Label statusLbl = new Label()
{
Name = "statusLbl",
Location = new Point( 70, percentLbl.Location.Y),
AutoSize = true,
Text = "Status: " + Status,
};
downloadItem.Controls.Add(statusLbl);
Button pauseBtn = new Button()
{
Name = "pauseBtn",
AutoSize=true,
Location = new Point(3,percentLbl.Location.Y+ percentLbl.Height+5),
Text="Pause",
Enabled=true,
};
downloadItem.Controls.Add(pauseBtn);
pauseBtn.Click += PauseBtn_Click;
Button resumeBtn = new Button()
{
Name = "resumeBtn",
AutoSize = true,
Location = new Point(pauseBtn.Width+pauseBtn.Location.X+5, pauseBtn.Location.Y),
Text = "Resume",
Enabled = true,
};
downloadItem.Controls.Add(resumeBtn);
resumeBtn.Click += ResumeBtn_Click;
Button openBtn = new Button()
{
Name = "openBtn",
AutoSize = true,
Location = new Point(resumeBtn.Width + resumeBtn.Location.X + 15, resumeBtn.Location.Y),
Text = "Open",
Enabled = true,
Tag = fileName,
};
downloadItem.Controls.Add(openBtn);
openBtn.Click += Open_Click;
downloadsMenu.Controls.Add(downloadItem);
}
//NEW
public void SETDownloadMenuItemSTATUS(string Status, int Id)
{
var item = downloadsMenu.Controls[Id.ToString()];
if (item != null)
{
item.Controls["statusLbl"].Text = Status;
}
}
public void SETDownloadMenuItemADD(int Id, string ReceivedBytes, int PercentComplete, string CurrentSpeed) //EDIT
{
// MessageBox.Show("Status:"+Status+" ID:"+Id+" Received:"+ReceivedBytes+" Percent:"+PercentComplete+" Current:"+CurrentSpeed,"on download");
var item = downloadsMenu.Controls[Id.ToString()];
if (item != null)
{
item.Controls["percentLbl"].Text = "% " + PercentComplete;
(item.Controls["downlaodProgress"] as ProgressBar).Value = PercentComplete;
item.Controls["receivedLbl"].Text = "Received: " + ReceivedBytes + "\nSpeed: " + CurrentSpeed;
if (PercentComplete == 100)
{
item.Controls["resumeBtn"].Enabled = false;
item.Controls["pauseBtn"].Enabled = false;
item.Controls["openBtn"].Enabled = true;
}
else
{
item.Controls["openBtn"].Enabled = false;
}
}
}
private void Open_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string downloadFilePath = FilePath + "\\" + btn.Tag;
if (File.Exists(downloadFilePath) == true)
{
try
{
System.Diagnostics.Process.Start(downloadFilePath);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error opening file!",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
else
{
MessageBox.Show("Error Path: "+ downloadFilePath, "Error! File not found.",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
private void PauseBtn_Click(object sender, EventArgs e)//EDIT
{
Button btn = (Button)sender;
downer.temp = btn.Tag.ToString(); //btn.tag, downloadItem.Id is SAME
downer.pause = true;
downer.resume = false;
}
private void ResumeBtn_Click(object sender, EventArgs e)//EDIT
{
Button btn = (Button)sender;
downer.temp = btn.Tag.ToString();
downer.resume = true;
downer.pause = false;
}
}
}