使用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[] { ',' }, 2)[0] + ".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 = 0; i < shelveList.Count; i++) { //循环最大粒子,在这个最大粒子当中来组织Json for (int g = 0; g < 4; g++) { for (int l = 0; l < 4; 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(2); // 新式注入 CefSharp.BindObjectAsync("bound"); } </script>
随后我们就可以通过bound这个对象来请求后台了
bound.GetobjBySline_Code(Sline_Code);
就以我来说,千万不要拿Jquery和Vue一起用,真的是太糟心了..
<body>
<div class="container" id="app" style="max- 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; 100%;">
<ul class="nav nav-pills nav-fill" id="nav_list">
<li class="nav-item" v-for="(item,index) in line_item">
<!-- 如果 index 1-->
<a class="nav-link active" key="item.Sline_code" @click="toggle(index,item)" v-if="index==0">{{item.Sline_name}}</a>
<!-- index 2 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'); 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(2);
// 新式注入
CefSharp.BindObjectAsync("bound");
}
</script>
<script>
function loadScrollWidth(num) {
var tags = document.getElementsByClassName('line_div')[0];
tags.style.width = num * 590 + 'px';
}
function changedom(listdata,shelvedata) {
var num = 1;
$(".custormTable").html("");
shelvedata.shift();
for (var i = 0; i < shelvedata.length; i++) {
var shelve_code = shelvedata[i].shelve_code;
//不管如何都是循环4X4
for (var y = 0; y < 4; y++) {
var goodshtml = '<tbody><tr class="store_goodsName">';
var numhtml = '<tr class="store_goodsId">'
numhtml += "<td>" + num + "</td>";
numhtml += "<td>" + (num + 1) + "</td>";
numhtml += "<td>" + (num + 2) + "</td>";
numhtml += "<td>" + (num + 3) + "</td>";
numhtml = numhtml + '</tr>';
for (var g = 0; g < 4; 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 + 4;
}
}
}
</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=0;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 < 2) {
loadScrollWidth(2);
} 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)(() => { 。。。。。。。。。 } }