使用CefSharp在.NET中嵌入Google kernel
原文:使用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的更多相关文章
- 在VC/MFC中嵌入Google地图——图文并茂
近期须要实验室须要将在无人机地面站中嵌入地图,在网上找了非常多资料,最终有些眉目了, 首先.做这个须要用到的知识有.MFC控件.MFC类库.JavaScript脚本语言.Google API.Goog ...
- 使用CefSharp在.NET中嵌入Chromium
使用CefSharp可以在.NET轻松的嵌入Html,不用担心WPF与Winform 控件与它的兼容性问题,CefSharp大部分的代码是C#,它可以在VB或者其他.NET平台语言中来进行使用. 近几 ...
- 网页中嵌入google地图
一丶前言 大致需求:美国地图中标记分布的仓库图钉(鼠标经过显示地址详情),通过输入寄收件地邮编来在地图上定位位置添加图钉,将寄件地,选择的仓库,收件地图钉折线相连接,表示大致路线. 一丶google开 ...
- 转-使用 CefSharp 在 C# App 中嵌入 Chrome 浏览器
使用 CefSharp 在 C# App 中嵌入 Chrome 浏览器 2016-09-23 分类:.NET开发.编程开发.首页精华0人评论 分享到:更多3 本文由码农网 – 小峰原创翻译,转载 ...
- 使用CefSharp在.Net程序中嵌入Chrome浏览器(一)——简介
有的时候,我们需要在程序中嵌入Web浏览器,其实.Net Framework中本身就提供了WebBrowser控件,本身这个是最简单易用的方案,但不知道是什么原因,这个控件在浏览网页的时候有些莫名的卡 ...
- 使用CefSharp在.Net程序中嵌入Chrome浏览器(二)——参数设置
在实现了.Net程序中嵌入Chrome浏览器后,下一步的个性化操作就是加入一些设置了,在前面的文章中,我们可以看到在使用Chrome控件前,有如下一个操作: var setting = new Cef ...
- 在Flex (Flash)中嵌入HTML 代码或页面—Flex IFrame
在flex组件中嵌入html代码,可以利用flex iframe.这个在很多时候会用到的,有时候flex必须得这样做,如果你不这样做还真不行-- flex而且可以和html进行JavaScript交互 ...
- [转]在 Eclipse 中嵌入 NASA World Wind Java SDK
使用此开源 SDK 开发 GIS 应用程序 NASA 开发的开源 World Wind Java (WWJ) SDK 为地理信息系统(Geographic Information Systems,GI ...
- 在Flex (Flash)中嵌入HTML 代码或页面—Flex IFrame
在flex组件中嵌入html代码,可以利用flex iframe.这个在很多时候会用到的,有时候flex必须得这样做,如果你不这样做还真不行…… flex而且可以和html进行JavaScript交互 ...
随机推荐
- 为什么要使用 Go 语言,Go 语言的优势在哪里?
1.Go有什么优势 可直接编译成机器码,不依赖其他库,glibc的版本有一定要求,部署就是扔一个文件上去就完成了. 静态类型语言,但是有动态语言的感觉,静态类型的语言就是可以在编译的时候检查出来隐藏的 ...
- JavaScript疑难杂症系列-事件
事件这块知识点虽然是老生长谈的,但对于我来说多多整理,多多感悟,温故知新,每次看看这块都有不同的收获.(在这里我不会长篇大论,只会挑重点;具体的小伙伴们自行查找) 什么是事件 在编程时系统内发生的动作 ...
- C++入门经典-例3.8-使用条件表达式判断一个数是否是3和5的整倍数
1:代码如下: // 3.8.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include<iostream> using ...
- Docker报错: TLS handshake timeout”。
Docker 默认拉取国外镜像,换成国内就搞定. 为了永久性保留更改,您可以修改 /etc/docker/daemon.json 文件并添加上 registry-mirrors 键值. { &quo ...
- Laravel框架之获取URL地址
1. 使用 Request 类: $url = Request::getRequestUri(); 2. 使用 $request 对象: public function show(Request $r ...
- (组件的)状态(state)和属性(props)之间有何不同
State 是一种数据结构,用于组件挂载时所需数据的默认值.State 可能会随着时间的推移而发生突变,但多数时候是作为用户事件行为的结果.Props(properties 的简写)则是组件的配置.p ...
- leetcode-easy-trees-98. Validate Binary Search Tree-NO
mycode 不会 注意:root的值要比左子树上所有的数大 参考 # Definition for a binary tree node. # class TreeNode(object): # ...
- oracle字段like多个条件
写oracle sql时有时候会有 and (字段 like ‘匹配串1’or 字段 like ‘匹配串2’or ...)这样的情况出现,下面提供一个简洁点的解决方案: and REGEXP_LIKE ...
- css中相对定位和绝对定位
相对定位: #box_relative { position: relative; left: 30px; top: 20px; } 绝对定位: #box_relative { position: a ...
- windows 10 右键菜单 使用vscode打开 快捷键
呼出菜单栏(鼠标右键或快捷键shift+f10)之后按i 资料: 1.如何为windows 10添加右键context menu item https://stackoverflow.com/ques ...