原文: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");//PepperFlash\manifest.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 KeyBoardHander : IKeyboardHandler
    {
        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;
            const int VK_F5 = 0x74;
            if (windowsKeyCode == VK_F5)
            {
                browser.Reload(); //此处可以添加想要实现的代码段
            }
            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

posted on 2019-06-12 15:35 NET未来之路 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/11010018.html

GitHub 加速计划 / de / devtools
24.6 K
4.14 K
下载
vuejs/devtools: Vue.js 开发者工具,这是一个浏览器插件,可以安装在 Chrome 和 Firefox 等现代浏览器中,用于调试 Vue 应用程序,提供了组件树查看、状态快照、时间旅行等高级调试功能。
最近提交(Master分支:3 个月前 )
79116147 - 4 个月前
f0359002 - 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐