CefSharp的简单应用,制作自动学习视频软件(基于Chromium)

CefSharp在NuGet的简介是“The CefSharp Chromium-based browser component”,机翻的意思就是“基于Cefsharp Chromium的浏览器组件”

请注意本文不会有太多功能的详细介绍,只有实现相关需求的基本功能

请注意本次使用CefSharp版本为57.0.0,最新版本可能相关用法已经不适用

播放视频需安装相关Flash软件才能播放

 

本次编写要实现的主要功能是

1:播放视频,

    (本次打开指定网址默认会播放视频)

2:自动跳转下一条视频,

    (学习进度100%时跳转下一个网址)

3:自动点击验证

    (执行JavaScript代码)

成品软件界面如下

一:添加相关引用,NuGet 搜索安装 CefSharp.WinForms,CefSharp.Common(本次使用版本为57.0.0)

 

二:项目属性中平台要进行设置

三:编写代码

      具体实现方式是,有两个窗口,一个浏览学习列表页(获取内页学习页面链接),另一个浏览内页学习页面进行学习

  CefSharp.WinForms.ChromiumWebBrowser browser = null;

  CefSharp.WinForms.ChromiumWebBrowser browserChild = null;

public Form1()
        {
            InitializeComponent();
            //必须进行初始化,否则出不来页面啦。
            CefSharp.Cef.Initialize();

            //实例化控件 即课程列表页查看和获取具体学习页面路径
            browser = new CefSharp.WinForms.ChromiumWebBrowser("http://xxx.xxx.cn");
            //设置停靠方式
            browser.Dock = DockStyle.Fill;
            //加入到当前窗体中
            this.tabControl1.TabPages[0].Controls.Add(browser);
            //绑定新窗口打开事件
            browser.LifeSpanHandler = new NewWindowCreatedEventHandler();
            //browser.LoadHandler = new NewLoadHandler();
            //browser.FrameLoadEnd += Browser_FrameLoadEnd;

            //实例化子控件 即学习页面
            browserChild = new CefSharp.WinForms.ChromiumWebBrowser("about:blank");
            //设置停靠方式
            browserChild.Dock = DockStyle.Fill;
            //加入到当前窗体中
            this.tabControl1.TabPages[1].Controls.Add(browserChild);
            Control.CheckForIllegalCrossThreadCalls = false;//防止出现  线程间操作无效:
        }
        /// <summary>
        /// 打开新窗口事件处理(在当前浏览器窗口打开)
        /// </summary>
        internal class NewWindowCreatedEventHandler : ILifeSpanHandler
        {
            public bool DoClose(IWebBrowser browserControl, IBrowser browser)
            {
                return false;
            }

            public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
            {

            }

            public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser)
            {

            }

            public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl,
    string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures,
    IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
            {
                newBrowser = null;
                var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
                chromiumWebBrowser.Load(targetUrl);
                return true; //Return true to cancel the popup creation copyright by codebye.com.
            }
        }

 执行JavaScript代码方法

string BrowserEvaluateScriptAsync(string scriptStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("function tempFunction() {");
            sb.AppendLine(scriptStr);
            sb.AppendLine("}");
            sb.AppendLine("tempFunction();");
            string resultStr = "";
            try
            {
                var task = browser.GetBrowser().GetFrame(browser.GetBrowser().GetFrameNames()[0]).EvaluateScriptAsync(sb.ToString());
                task.ContinueWith(t =>
                {
                    if (!t.IsFaulted)
                    {
                        var response = t.Result;
                        if (response.Success == true)
                        {
                            if (response.Result != null)
                            {
                                resultStr = response.Result.ToString();
                            }
                        }
                    }
                }, TaskScheduler.FromCurrentSynchronizationContext());
                return resultStr;
            }
            catch (Exception ex)
            {
                return resultStr;
            }
        }

 获取内页学习页面链接代码,实现方式是获取页面的html然后用正则表达式去匹配当前页的链接

//获取课程列表
        private void GetDataList_Click(object sender, EventArgs e)
        {
            Log("获取课程列表");
            if (browser != null)
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("function tempFunction() {");
                    sb.AppendLine(" return document.body.innerHTML; ");
                    sb.AppendLine("}");
                    sb.AppendLine("tempFunction();");
                    var task = browser.GetBrowser().GetFrame(browser.GetBrowser().GetFrameNames()[0]).EvaluateScriptAsync(sb.ToString());
                    task.ContinueWith(t =>
                    {
                        if (!t.IsFaulted)
                        {
                            var response = t.Result;
                            if (response.Success == true)
                            {
                                if (response.Result != null)
                                {
                                    string resultStr = response.Result.ToString();
                                    Regex r = new Regex("(/knowledge/document/[\\S]*.html)|(/knowledge/video/[\\S]*.html)|(/package/video/[\\S]*.html)|(/package/document/[\\S]*.html)|(/knowledge/scorm/[\\S]*.html)|(/package/scorm/[\\S]*.html)|(/package/ebook/[\\S]*.html)");//构造表达式package/scorm
                                        MatchCollection matches = r.Matches(resultStr);
                                    foreach (Match match in matches)
                                    {
                                        string word = match.Groups["word"].Value;
                                        int index = match.Index;
                                        richTextBox1.AppendText(match.Value.Replace("\"", ""));
                                        richTextBox1.AppendText("\r\n");
                                    }
                                    SetConfig(LastHistroyDataList, richTextBox1.Text);
                                    Log("获取课程列表成功!(添加" + matches.Count.ToString() + "列数据)");
                                    tabControl1.SelectedIndex = 2;
                                }
                            }
                        }
                    }, TaskScheduler.FromCurrentSynchronizationContext());
                }
                catch (Exception ex)
                {
                    Log("获取课程列表失败!(js执行失败)");
                }
            }
            else
            {
                Log("获取课程列表失败!(浏览器获取失败)");
            }
        }

 接下来定时判断具体学习页面是否到达100%的进度,如果达到100%的进度,浏览下一个链接即可

//判断页面是否显示 “已经完成学习”
        string PanDuanWanCheng()
        {
            if (browserChild != null)
            {
                try
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("function tempFunction() {");
                    sb.AppendLine("return document.getElementById('ScheduleText').innerText;");
                    sb.AppendLine("}");
                    sb.AppendLine("tempFunction();");
                    string resultStr = "";
                    var task = browserChild.GetBrowser().GetFrame(browserChild.GetBrowser().GetFrameNames()[0]).EvaluateScriptAsync(sb.ToString());
                    task.ContinueWith(t =>
                    {
                        if (!t.IsFaulted)
                        {
                            var response = t.Result;
                            if (response.Success == true)
                            {
                                if (response.Result != null)
                                {
                                    resultStr = response.Result.ToString();
                                    if (resultStr == "100%")
                                    {
                                        string nowLearnTitle = GetNowLearnTitle();
                                        //Log("课程已完成!" + browserChild.Url.ToString() + "(" + nowLearnTitle + ")");
                                        //完成操作
                                        if (learnWithDataList)
                                        {
                                            BroserChildStarWithDataList();
                                        }
                                        return "1";
                                    }
                                }
                            }
                        }
                        return "0";
                    }, TaskScheduler.FromCurrentSynchronizationContext());
                }
                catch (Exception ex)
                { }
            }
            return "0";
        }

 

posted @ 2019-02-16 12:37  蒲公英C  阅读(2832)  评论(0编辑  收藏  举报