原文:使用CefSharp在.NET中嵌入Google kernel

  使用CefSharp可以在.NET轻松的嵌入Html,不用担心WPF与Winform 控件与它的兼容性问题,CefSharp大部分的代码是C#,它可以在VB或者其他.NET平台语言中来进行使用。

  近几天来,公司项目中需要使用WebBrowser,其中考虑了几个控件,如1.Winform中的WebBrowser    2.WPF中的WebBrowser    3.WebKit.Net     4.CefSharp

  Winform的WebBrowser放到项目中进行了实验和处理,发现致命问题:AllowsTransparency = true 和 Webbrowser 等内置窗体显示冲突,导致不发选择,还有就是GC回收不及时,一下子就飙到了100MB+.

  后来考虑WPF的webbrowser 它实际上还是封装了Winform,有个严重的问题就是它一直置顶到最顶层,so,无法选择。

  再后来考虑WebKit.Net ,但发现已经N多年没有更新,所以不在考虑...

  最后跌跌撞撞跑到CefSharp,发现非常的坑啊!!竟然不支持AnyCPU,关键是我的项目中有的功能是必须AnyCpu启动的啊!还好,官方在去年已经公布了支持AnyCpu的方法。

  首先Nuget引用cefsharp.WPF,它会自己引用Common,其他不用管。我们还需要再App.xaml.cs中添加代码来支持AnyCpu。

    public partial class App : Application
{
public App()
{
//Add Custom assembly resolver
AppDomain.CurrentDomain.AssemblyResolve += Resolver; //Any CefSharp references have to be in another method with NonInlining
// attribute so the assembly rolver has time to do it's thing.
InitializeCefSharp();
} [MethodImpl(MethodImplOptions.NoInlining)]
private static void InitializeCefSharp()
{
var settings = new CefSettings(); // Set BrowserSubProcessPath based on app bitness at runtime
settings.BrowserSubprocessPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
Environment.Is64BitProcess ? "x64" : "x86",
"CefSharp.BrowserSubprocess.exe"); // Make sure you set performDependencyCheck false
Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);
} // Will attempt to load missing assembly from either x86 or x64 subdir
// Required by CefSharp to load the unmanaged dependencies when running using AnyCPU
private static Assembly Resolver(object sender, ResolveEventArgs args)
{
if (args.Name.StartsWith("CefSharp"))
{
string assemblyName = args.Name.Split(new[] { ',' }, )[] + ".dll";
string archSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
Environment.Is64BitProcess ? "x64" : "x86",
assemblyName); return File.Exists(archSpecificPath)
? Assembly.LoadFile(archSpecificPath)
: null;
} return null;
}
private void Application_Startup(object sender, StartupEventArgs e)
{
}
}

  还没完,之后你得在你项目的 *.csproj 中添加一行配置,它是在你的第一个PropertyGroup中添加的。

最后一步,在App.config中配置x86,当然不是说不支持CPU,刚刚App.xaml.cs中我们已经修改了啊。

<configuration>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<probing privatePath="x86"/>
</assemblyBinding>
</runtime>
</...>

就现在我们在页面中添加一个CefSharpBrowser在grid中,您需要在容器空间中添加name 标记。

 public static ChromiumWebBrowser cefSha { get; set; }
public Visualization()
{
InitializeComponent();
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
cefSha = new ChromiumWebBrowser(Environment.CurrentDirectory + "/../../Pages/STORE/VisualizationHtml/StoreData.html"); // 页面加载完毕后打开开发者工具
cefSha.KeyboardHandler = new CEFKeyBoardHander();
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
NewMutliPage();
this.grid.Children.Add(cefSha);//初始化
}

前后端交互都是在NewMutliPage中搭起的桥梁,该代码是新版本的配置方式,大概是18年底,前后端的钩子可以通过bound来偷取。

public void NewMutliPage()
{
cefSha.JavascriptObjectRepository.ResolveObject += (s, eve) =>
{
var repo = eve.ObjectRepository;
if (eve.ObjectName == "bound")
{
repo.Register("bound", new JsEvent(), isAsync: true,
options: new BindingOptions()
{
CamelCaseJavascriptNames = false
});
}
};
}

老版本你可以这么配置前后端交互的桥梁。

public void OldSinglePage()
{
// 新版本默认为 false
CefSharpSettings.LegacyJavascriptBindingEnabled = true;
// 把 TestClass 注入到单个页面,名称为 test
_chromiumWebBrowser.RegisterJsObject("testold", new TestClass());
}
 LegacyJavascriptBindingEnabled 该属性就是让WebBrowser与WPF支持js交互,否则不可以建立jsObject 这个对象。

在 RegisterJsObject 中我们是绑定的类,该类中是我们后台向WebBrowser的所有数据方法。
public class JsEvent
{
/// <summary>
/// 根据货架列代码区查相关信息
/// </summary>
/// <param name="Sline_code"></param>
public void GetobjBySline_Code(string Sline_code)
{
Visualization.cefSha.ExecuteScriptAsync($@"getgoods({
Newtonsoft.Json.JsonConvert.SerializeObject(VisualizationDAL.GetList(Sline_code))});");
}
/// <summary>
/// 获取货架信息
/// </summary>
/// <param name="Sline_code"></param>
public void GetShelveDetail(string Sline_code)
{
//1.找到那列的所有货架
ObservableCollection<STORE_SHELVE> shelveList = XDAL.STORE_SHELVE_DAL.GetListByLineName(Sline_code);
//2.找到关于该列下所有的商品信息
ObservableCollection<STORe_DetailVm> detailList = new ObservableCollection<STORe_DetailVm>();
foreach (var item in shelveList)
{
XDAL.STORE_goods_Detail.GetGoodsDetail(item.Shelve_code).ToList().ForEach(obj =>
{
detailList.Add(obj);
});
}
#region
List<VisualShelveVm> VisualList = new List<VisualShelveVm>();
for (int i = ; i < shelveList.Count; i++)
{
//循环最大粒子,在这个最大粒子当中来组织Json
for (int g = ; g < ; g++)
{
for (int l = ; l < ; l++)
{
var store_detail = detailList.FirstOrDefault(a => a.grid == g.ToString()
&& a.Shelve_code == shelveList[i].Shelve_code
&& a.layer == l.ToString());
//如果未出库的里没有这个 那就可以添加
if (store_detail != null)
{
VisualList.Add(new VisualShelveVm()
{
shelve_grid = g.ToString(),
shelve_layer = l.ToString(),
shelve_code = shelveList[i].Shelve_code,
shelve_name = shelveList[i].Shelve_name,
isHas = true,
goods_code = store_detail.Goods_code,
goods_name = store_detail.Goods_name
});
}
else
{
VisualList.Add(new VisualShelveVm()
{
isHas = false,
shelve_grid = g.ToString(),
shelve_layer = l.ToString(),
});
}
}
}
}
#endregion
Visualization.cefSha.ExecuteScriptAsync($@"GetShelve({Newtonsoft.Json.JsonConvert.SerializeObject(VisualList)});");
}

  需要注意的是该代码块的最后一行,这是我们用前端方法的方式,Visualization是我们刚才的页面,我们直接调用静态CefSha然后执行它的异步方法,其中是直接执行的Js,它和Wpf自带的WebBrowser还不一样,微软的WebBrowser是高度封装的,而cefsha是高度开源的,这一块不得不赞了。

  前台如何请求后台呢?首先在页面加载的时候配置下bound对象。

<script>
window.onload = function () {
loadScrollWidth();
// 新式注入
CefSharp.BindObjectAsync("bound");
}
</script>

随后我们就可以通过bound这个对象来请求后台了

bound.GetobjBySline_Code(Sline_Code);

就以我来说,千万不要拿Jquery和Vue一起用,真的是太糟心了..

<body>
<div class="container" id="app" style="max-width: 1600px;">
<div class="row">
<div class="col-lg-3">
<div class="card">
<h3 class="card-img-top headtext">清单</h3>
<div class="card-body">
<table class="table table-striped">
<thead>
<tr>
<th scope="col">分类名称</th>
<th scope="col">数量</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in goods_item">
<th scope="row">{{item.goods_Name}}</th>
<td>{{item.num}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<div class="col-lg-9" style="overflow: scroll;">
<div class="row line_div">
<div class="row" style="font-size: 20px;background-color: #CCC;width: 100%;">
<ul class="nav nav-pills nav-fill" id="nav_list">
<li class="nav-item" v-for="(item,index) in line_item">
<!-- 如果 index -->
<a class="nav-link active" key="item.Sline_code" @click="toggle(index,item)" v-if="index==0">{{item.Sline_name}}</a>
<!-- index n -->
<a class="nav-link" key="item.Sline_code" @click="toggle(index,item)" v-if="index!=0">{{item.Sline_name}}</a>
</li>
</ul>
</div>
<div class="row" style="margin-left: 0;" id="VisualBody">
<div class="colums" v-for="item in reversedMessage">
<div class="row">
<img src="tx_3.png">
<div class="table_div">
<table class="custormTable" style="margin-top: 40px;" :id="item.code">
</table>
</div>
</div>
<div class="row"
style="background-image: url('tx_2.png');width: 556px;height:464px;background-repeat: repeat-y;">
</div>
<div class="row">
<img src="tx_1.png">
<div class="hj_center">
<h3>{{item.name}}</h3>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script>
window.onload = function () {
loadScrollWidth();
// 新式注入
CefSharp.BindObjectAsync("bound");
}
</script>
<script>
function loadScrollWidth(num) {
var tags = document.getElementsByClassName('line_div')[];
tags.style.width = num * + 'px';
}
function changedom(listdata,shelvedata) {
var num = ;
$(".custormTable").html("");
shelvedata.shift(); for (var i = ; i < shelvedata.length; i++) {
var shelve_code = shelvedata[i].shelve_code;
//不管如何都是循环4X4
for (var y = ; y < ; y++) {
var goodshtml = '<tbody><tr class="store_goodsName">';
var numhtml = '<tr class="store_goodsId">'
numhtml += "<td>" + num + "</td>";
numhtml += "<td>" + (num + ) + "</td>";
numhtml += "<td>" + (num + ) + "</td>";
numhtml += "<td>" + (num + ) + "</td>";
numhtml = numhtml + '</tr>';
for (var g = ; g < ; g++) {
var obj = listdata.find(item => item.shelve_layer == y && item.shelve_grid == g && item.shelve_code == shelve_code);
if (obj != null) {
if (obj.isHas == true) {
goodshtml = goodshtml + "<td>" + obj.goods_name + "</td>";
}
} else {
goodshtml = goodshtml + "<td></td>";
}
}
goodshtml = goodshtml + '</tr>' + numhtml + '</tbody>';
var my_element = $("#" + shelve_code);
$("#" + shelve_code).append(goodshtml);
num = num + ;
}
}
} </script>
</html>
<script>
var app = new Vue({
el: "#app",
data: {
m: "hello",
line_item: [],//列
goods_item: [],//商品列表+num
shelve_list: [],//货架列表
Listdata: [],//商品列表 },mounted() {
//全局钩子引用
window.getalert = this.getalert;
window.getgoods = this.getgoods;
window.GetShelve = this.GetShelve;
window.DBTwo = this.DBTwo;
},methods: {
getalert: function (list) {
this.line_item = typeof list == 'string' ? JSON.parse(list) : list;
},toggle:function(index,item){
$(".nav-item a").each(function () {
$(this).removeClass("active");
});
$(".nav-item a").eq(index).addClass('active');
//item 对象 Sline_Code 【字段】
var Sline_Code = item.Sline_code;
//调用完之后C#会找我们的一个方法然后将参数带过来
bound.GetShelveDetail(Sline_Code);
//请求后台,让后台直接调用一个方法去加载列表。
bound.GetobjBySline_Code(Sline_Code);
this.Wecas(index, item);
},Wecas: function (index, item) {
$(".nav-item a").each(function () {
$(this).removeClass("active");
});
$(".nav-item a").eq(index).addClass('active');
//item 对象 Sline_Code 【字段】
var Sline_Code = item.Sline_code;
//调用完之后C#会找我们的一个方法然后将参数带过来
bound.GetShelveDetail(Sline_Code);
//请求后台,让后台直接调用一个方法去加载列表。
bound.GetobjBySline_Code(Sline_Code);
},getgoods: function (goods_list) {
//该方法是返回货架有的物品
this.goods_item = typeof goods_list == 'string' ? JSON.parse(goods_list) : goods_list;
}, GetShelve: function (list) {
this.Listdata = list;
let obj = {};
list = list.reduce((cur, next) => {
obj[next.shelve_code] ? "" : obj[next.shelve_code] = true && cur.push(next);
return cur;
}, []);
this.shelve_list = typeof list == 'string' ? JSON.parse(list) : list;
changedom(this.Listdata, this.shelve_list);
}
}, computed: {
//所有的货架列出来
reversedMessage: function () {
var array = [];
for(var i=;i<this.shelve_list.length;i++){
//判断是否name是不是有
if (this.shelve_list[i].shelve_name != null) {
var obj = {
name: this.shelve_list[i].shelve_name,
code : this.shelve_list[i].shelve_code
}
array.push(obj);
}
}
if (array.length < ) {
loadScrollWidth(); } else {
loadScrollWidth(array.length);
}
return array;
}
}
});
</script>

  前后端交互最好是前端请求后端,然后让后端执行前端的Js带上参数。

需要注意的cefsharp初次调用js的是 cefSha.ExecuteScriptAsyncWhenPageLoaded($"getalert({str});");  我也是醉

  还有就是在开发中一定想要F12 看看代码运行状况如何或者要调试。

 class CEFKeyBoardHander : 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;
}
}
return false;
} public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
{
return false;
}
}

ok就这样·~效果图

2019/8/27 更新 cefsharp调用后台C#代码中 有操作UI的 则需要

public void Show(string Code)
{
App.Current.Dispatcher.Invoke((Action)(() =>
{
。。。。。。。。。
}
}

使用CefSharp在.NET中嵌入Google kernel的更多相关文章

  1. 在VC/MFC中嵌入Google地图——图文并茂

    近期须要实验室须要将在无人机地面站中嵌入地图,在网上找了非常多资料,最终有些眉目了, 首先.做这个须要用到的知识有.MFC控件.MFC类库.JavaScript脚本语言.Google API.Goog ...

  2. 使用CefSharp在.NET中嵌入Chromium

    使用CefSharp可以在.NET轻松的嵌入Html,不用担心WPF与Winform 控件与它的兼容性问题,CefSharp大部分的代码是C#,它可以在VB或者其他.NET平台语言中来进行使用. 近几 ...

  3. 网页中嵌入google地图

    一丶前言 大致需求:美国地图中标记分布的仓库图钉(鼠标经过显示地址详情),通过输入寄收件地邮编来在地图上定位位置添加图钉,将寄件地,选择的仓库,收件地图钉折线相连接,表示大致路线. 一丶google开 ...

  4. 转-使用 CefSharp 在 C# App 中嵌入 Chrome 浏览器

    使用 CefSharp 在 C# App 中嵌入 Chrome 浏览器 2016-09-23    分类:.NET开发.编程开发.首页精华0人评论 分享到:更多3 本文由码农网 – 小峰原创翻译,转载 ...

  5. 使用CefSharp在.Net程序中嵌入Chrome浏览器(一)——简介

    有的时候,我们需要在程序中嵌入Web浏览器,其实.Net Framework中本身就提供了WebBrowser控件,本身这个是最简单易用的方案,但不知道是什么原因,这个控件在浏览网页的时候有些莫名的卡 ...

  6. 使用CefSharp在.Net程序中嵌入Chrome浏览器(二)——参数设置

    在实现了.Net程序中嵌入Chrome浏览器后,下一步的个性化操作就是加入一些设置了,在前面的文章中,我们可以看到在使用Chrome控件前,有如下一个操作: var setting = new Cef ...

  7. 在Flex (Flash)中嵌入HTML 代码或页面—Flex IFrame

    在flex组件中嵌入html代码,可以利用flex iframe.这个在很多时候会用到的,有时候flex必须得这样做,如果你不这样做还真不行-- flex而且可以和html进行JavaScript交互 ...

  8. [转]在 Eclipse 中嵌入 NASA World Wind Java SDK

    使用此开源 SDK 开发 GIS 应用程序 NASA 开发的开源 World Wind Java (WWJ) SDK 为地理信息系统(Geographic Information Systems,GI ...

  9. 在Flex (Flash)中嵌入HTML 代码或页面—Flex IFrame

    在flex组件中嵌入html代码,可以利用flex iframe.这个在很多时候会用到的,有时候flex必须得这样做,如果你不这样做还真不行…… flex而且可以和html进行JavaScript交互 ...

随机推荐

  1. [笔记]MongoDB 二(Linux下MongoDB API C++编程)

    一.连接类 DBClientConnection,派生自DBClientBase.DBClientBase类是实现query, update, insert, remove等功能. 构造函数:DBCl ...

  2. php的intval函数

    PHP intval() 函数 PHP 可用的函数PHP 可用的函数 intval() 函数用于获取变量的整数值. intval() 函数通过使用指定的进制 . PHP , PHP , PHP 语法 ...

  3. 分布式-信息方式-ActiveMQ的静态网络连接

                           ActiveMQ的静态网络连接 在一台服务器上启动多个Broker步骤如下:1:把整个conf文件夹复制一份,比如叫做conf22:修改里面的 activ ...

  4. nginx 与location语法详解

    Location语法优先级排列   匹配符 匹配规则 优先级 = 精确匹配 1 ^~ 以某个字符串开头 2 ~ 区分大小写的正则匹配 3 ~* 不区分大小写的正则匹配 4 !~ 区分大小写不匹配的正则 ...

  5. Springboot 使用 webSocket

    介绍 WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议.在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进 ...

  6. mongo 是什么

    一.概述1.MongoDB是什么?用一句话总结MongoDB是一款为web应用程序和互联网基础设施设计的数据库管理系统.没错MongoDB就是数据库,是NoSQL类型的数据库 2.为什么要使用Mong ...

  7. python3笔记十八:python列表元组字典集合文件操作

    一:学习内容 列表元组字典集合文件操作 二:列表元组字典集合文件操作 代码: import pickle  #数据持久性模块 #封装的方法def OptionData(data,path):    # ...

  8. 快读模板&&快出模板

    inline int read() { ,b=; char c=getchar(); ') { if(c=='-') b=-; c=getchar(); } ') { a=(a<<)+(a ...

  9. IFB

    本文翻译自Linux官方IFB文档 IFB(中介功能块设备)是IMQ(中介队列设备)的继任者,IMQ从来没有被集成过,IFB拥有IMQ的优点,在SMP上更加清晰明了,并且代码量缩减了非常多,旧的中介设 ...

  10. [Python]操作shell脚本报错Permission denied

    问题: In []: os.system('./test_shell_no_para.sh') : ./test_shell_no_para.sh: Permission denied Out[]: ...