• CefSharp F12打开DevTools查看console js和c#方法互相调用


    winform嵌入chrome浏览器,修改项目属性 生成 平台为x86

    1.nuget安装cefsharp

    2.实例化浏览器

    ChromiumWebBrowser b;

    private void Form1_Load(object sender, EventArgs e)
    {

    CefSettings settings = new CefSettings();
    settings.CefCommandLineArgs.Add("--disable-web-security","1");//关闭同源策略,允许跨域
    settings.CefCommandLineArgs.Add("ppapi-flash-version", "18.0.0.209");//PepperFlashmanifest.json中的version
    settings.CefCommandLineArgs.Add("ppapi-flash-path", "PepperFlash\pepflashplayer.dll");
    settings.CefCommandLineArgs.Add("--enable-system-flash", "1");//使用系统flash
    Cef.Initialize(settings);

    /*以上设置未测试是否可行*/


    b = new ChromiumWebBrowser("http://localhost:57531/views/Map/scene.html");
    this.Controls.Add(b);
    b.Dock = DockStyle.Fill;
    b.KeyboardHandler = new CEFKeyBoardHander();
    }

    3.响应F12打开控制台console

    public class CEFKeyBoardHander : IKeyboardHandler
    {//https://bbs.csdn.net/topics/392375553
    public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
    {
    if (type == KeyType.KeyUp && Enum.IsDefined(typeof(Keys), windowsKeyCode))
    {
    var key = (Keys)windowsKeyCode;
    switch (key)
    {
    case Keys.F12:
    browser.ShowDevTools();
    break;

    case Keys.F5:

    if (modifiers == CefEventFlags.ControlDown)
    {
    //MessageBox.Show("ctrl+f5");
    browser.Reload(true); //强制忽略缓存

    }
    else
    {
    //MessageBox.Show("f5");
    browser.Reload();
    }
    break;


    }
    }
    return false;
    }

    public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
    {
    return false;
    }
    }

    3.js调用c#方法

    public class JsCallMethods
    {
    public string Test(string msg)
    {
    return "Return value:" + msg;


    /*如果此处要操作winform界面相关的,则需要使用beginInvoke将请求封送至winform主线程中,定义一个全局静态的主窗口类实例  public static Form1 MainForm;主窗体的load事件中MainForm=this;否则会报错:System.InvalidOperationException:“线程间操作无效: 从不是创建控件“Form1”的线程访问它。” 如果要在BeginInvoke之后返回值给前台请使用Invoke代替beginInvoke或者在返回值之前使用EndInvoke函数.

    Form1.MainForm.BeginInvoke(new Action(()=> {
    var frm = new XXWindow();
    frm.Show();

    /*Invoke之后返回值得情况示例*/

    var str = "";

    //Form1.MainForm.Invoke(...);
    var iresult=Form1.MainForm.BeginInvoke(new Action(() =>
    {
    if (frm != null && !frm.IsDisposed)
    {
    str=frm.PlayByIndex(index,brand,ip,port,user,pwd,channel,isMainStream);

    }
    else
    {
    str= "播放窗口未实例化.";
    Thread.Sleep(3000); //阻塞3s,后返回值给前台
    }
    }));
    ////while (!iresult.AsyncWaitHandle.WaitOne(-1, false))
    ////{
    //// Console.Write("*");
    ////}
    var obj=Form1.MainForm.EndInvoke(iresult);
    return str;

    */


    }));


    }
    }

    将以下代码加载Cef.Initialize(settings)之后

    CefSharpSettings.LegacyJavascriptBindingEnabled = true;//新cefsharp绑定需要优先申明

    browser.RegisterAsyncJsObject("MainForm", new JsCallMethods(), new CefSharp.BindingOptions() { CamelCaseJavascriptNames = false });
    Cef.AddCrossOriginWhitelistEntry("*", "http", "*", true);

    js调用并获取返回值:

    var promise = MainForm.Test("123");
    promise.then(function (v) {

    alert(v);
    })

     3.2下载文件

    public void Download(string path)
    {
    try
    {
    HttpDownloadFile(path, Application.StartupPath, true, (fileName, contenType, bytes, totalLength, streamLength) =>
    {
    System.Diagnostics.Process.Start(fileName);
    });
    }
    catch (Exception ex)
    {
    MessageBox.Show("操作失败:"+ex.Message);
    }
    }

    /// <summary>
    /// 文件下载
    /// </summary>
    /// <param name="url">所下载的路径</param>
    /// <param name="path">本地保存的路径</param>
    /// <param name="overwrite">当本地路径存在同名文件时是否覆盖</param>
    /// <param name="callback">实时状态回掉函数</param>
    /// Action<文件名,文件的二进制, 文件大小, 当前已上传大小>
    public static void HttpDownloadFile(string url, string path, bool overwrite, Action<string, string, byte[], long, long> callback = null)
    {
    // 设置参数
    HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
    //发送请求并获取相应回应数据
    HttpWebResponse response = request.GetResponse() as HttpWebResponse;
    //获取文件名
    string fileName = response.Headers["Content-Disposition"];//attachment;filename=FileName.txt
    string contentType = response.Headers["Content-Type"];//attachment;

    if (string.IsNullOrEmpty(fileName))
    fileName = response.ResponseUri.Segments[response.ResponseUri.Segments.Length - 1];
    else
    fileName = fileName.Remove(0, fileName.IndexOf("filename=") + 9);

    fileName = HttpUtility.UrlDecode(fileName);
    //直到request.GetResponse()程序才开始向目标网页发送Post请求
    using (Stream responseStream = response.GetResponseStream())
    {
    long totalLength = response.ContentLength;
    ///文件byte形式
    byte[] b =new byte[totalLength];
    //创建本地文件写入流
    if (System.IO.File.Exists(Path.Combine(path, fileName)))
    {
    fileName = DateTime.Now.Ticks + "-"+fileName ;
    }
    var fullPath = Path.Combine(path + "\downloads", fileName);
    using (Stream stream = new FileStream(fullPath, overwrite ? FileMode.Create : FileMode.CreateNew))
    {
    byte[] bArr = new byte[1024];
    int size;
    while ((size = responseStream.Read(bArr, 0, bArr.Length)) > 0)
    {
    stream.Write(bArr, 0, size);

    }
    }
    callback.Invoke(fullPath, contentType, b, totalLength, 0);
    }
    }

    js调用

     MainForm.Download("http://192.168.18.199/test.xls");


    4.c#调用js方法

    function jsMethod(param) {
    alert("jsMethod called param is :" + param);
    }

    C#调用

    b.ExecuteScriptAsync("jsMethod(123)");

    From: https://www.cnblogs.com/xuejianxiyang/p/9981398.html

  • 相关阅读:
    安装 pgadmin4 docker
    DevExpress 、XtraGrid 自定义统计数据
    LINQ之Join(from join on )与GroupJoin(from join on into)将两个集合进行关联与分组
    LINQ之LookUp
    LINQ之GroupBy(group p by into)
    LINQ之SelectMany(from.. from..复合from子句)
    Row_number over (Partition by yyy) in Entity Framework
    为表或者表字段添加扩展属性(MS_Description、sp_addextendedproperty、注释)
    学习vue,待续中。。。
    用Python爬取《王者荣耀》英雄皮肤数据并可视化分析,用图说话
  • 原文地址:https://www.cnblogs.com/xuejianxiyang/p/9981398.html
Copyright © 2020-2023  润新知