首页 > 解决方案 > 如何 Cefsharp 'callbak' 是 pause() 和 resume()?

问题描述

我想检查cefsharp chromiumbrowser 中的downloadHandler。我的目标是暂停和恢复任何下载。为此,我尝试了 downloadHandler 中callback.pause ()callback.resume ()命令。但是我遇到了一些问题,我该如何解决呢?

问题:

视频:https ://youtu.be/3A_HHrEJfTM

工作原则:

截图

1)开始下载

2)点击暂停按钮

3)callback.resume() 不起作用

编码所有 DownloadHandler.cs [编辑]

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;
    }
}
}

编写一点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;
    }
}
}

标签: c#downloadcefsharpchromium-embedded

解决方案


推荐阅读