文章目录

  • 0. 简介
  • 1. 安装
  • 2. H.264支持
  • 3. 加载本地HTML文件
  • 4. 多个窗口显示浏览器
  • 5. 执行JavaScript代码
  • 6. 在JS中调用C#方法

0. 简介

CefSharp,简单来说就是一款.Net编写的浏览器包,方便你在Winform和WPF中内嵌的Chrome浏览器组件。它支持HTML5。
CefSharp的功能比较复杂,以下只介绍一些我觉得比较重要的并且目前经常用的功能。

1. 安装

CefSharp的安装过程如下:

  1. 打开Visual Stduio,新建一个Windows窗体应用(.NET Framework)
  2. 在“工具”菜单打开NuGet包管理器;
  3. 搜索“CefSharp.WinForms”进行安装;
  4. CefSharp不能在“Any CPU”平台上运行,需要配置。打开“配置管理器”;
  5. 新建“x86”和“x64”两个平台。从理论上来说使用x86或者x64平台都行,但由于之后要使用编译好的支持h264的x86内核,因此此处选择x86平台;
  6. 在 Form1.cs 中添加如下代码;
using CefSharp;
using CefSharp.WinForms;
using System;
using System.Windows.Forms;namespace WindowsFormsApp8 {public partial class Form1 : Form {ChromiumWebBrowser browser;public void InitBrowser() {CefSettings settings = new CefSettings();// Note that if you get an error or a white screen, you may be doing something wrong !// Try to load a local file that you're sure that exists and give the complete path instead to test// for example, replace page with a direct path instead :// String page = @"C:\Users\SDkCarlos\Desktop\afolder\index.html";// String page = string.Format(@"{0}\html-resources\html\index.html", Application.StartupPath);String url = "http://www.html5test.com";// Initialize cef with the provided settingsCef.Initialize(settings);// Create a browser componentbrowser = new ChromiumWebBrowser(url);// Add it to the form and fill it to the form window.this.Controls.Add(browser);browser.Dock = DockStyle.Fill;// Allow the use of local resources in the browserBrowserSettings browserSettings = new BrowserSettings();browserSettings.FileAccessFromFileUrls = CefState.Enabled;browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;browser.BrowserSettings = browserSettings;}public Form1() {InitializeComponent();InitBrowser();}}
}
  1. 调试程序,发现窗口有白边,原因是没有设置高分屏适配,按照C# WinForm程序设计的第1.3节的方法设置即可;
  2. 调试程序,得到最终效果。

2. H.264支持

默认情况下,CefSharp是不支持H.264的,因此不可以进行视频播放。为了使其支持视频播放,需要修改其内核文件,操作步骤如下:
注:请确保安装的CefSharp.WinForms是79.1.360版本的!

  1. 下载我的老师(感谢他!)编译好的支持H264的内核文件 libcef.dll ;
    链接:下载地址
    提取码:8q2u
  2. 用其替换packages目录下的同名文件;
  3. 调试程序,查看效果。显然浏览器已支持H.264。

3. 加载本地HTML文件

除了使用CefSharp浏览器访问网络地址,还有一个重要的用途就是访问本地文件。
首先将需要用到的HTML和其他静态文件拷贝到工程目录,并设置“复制到输出目录”:

然后编写如下代码:

using CefSharp;
using CefSharp.WinForms;
using System;
using System.IO;
using System.Windows.Forms;namespace WindowsFormsApp8 {public partial class Form1 : Form {ChromiumWebBrowser browser;public void InitBrowser() {CefSettings settings = new CefSettings();// Note that if you get an error or a white screen, you may be doing something wrong !// Try to load a local file that you're sure that exists and give the complete path instead to test// for example, replace page with a direct path instead :// String page = @"C:\Users\SDkCarlos\Desktop\afolder\index.html";// String page = string.Format(@"{0}\html-resources\html\index.html", Application.StartupPath);String url = string.Format(@"{0}\ui\test.html", Application.StartupPath);if (!File.Exists(url)) {MessageBox.Show("Error: File doesn't exists : " + url);}// Initialize cef with the provided settingsCef.Initialize(settings);// Create a browser componentbrowser = new ChromiumWebBrowser(url);// Add it to the form and fill it to the form window.this.Controls.Add(browser);browser.Dock = DockStyle.Fill;// Allow the use of local resources in the browserBrowserSettings browserSettings = new BrowserSettings();browserSettings.FileAccessFromFileUrls = CefState.Enabled;browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;browser.BrowserSettings = browserSettings;}public Form1() {InitializeComponent();InitBrowser();}}
}

调试程序,可以看到效果:

4. 多个窗口显示浏览器

如果有多个窗口都需要显示浏览器,每个窗口的代码并不完全相同。
主窗口的代码如上一节所示,新的窗口的代码如下:

using System;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.IO;namespace WindowsFormsApp8 {public partial class Form2 : Form {ChromiumWebBrowser browser;public void InitBrowser() {String url = string.Format(@"{0}\ui\test.html", Application.StartupPath);if (!File.Exists(url)) {MessageBox.Show("Error: File doesn't exists : " + url);}browser = new ChromiumWebBrowser(url);this.Controls.Add(browser);browser.Dock = DockStyle.Fill;}public Form2() {InitializeComponent();InitBrowser();}}
}

显然,与主窗口的区别是去掉了“Cef.Initialize()”部分。
运行效果如下:

5. 执行JavaScript代码

如果需要通过程序控制网页的显示、流程,最明显的方法莫过于执行JavaScript代码了。特别是如果使用Vue.js框架,那么通过JS可以实现“模板渲染”的功能。以下展示了一个示例。
注意:ExecuteScriptAsync()方法是异步执行的,程序并不会阻塞!

  1. 编辑HTML文件(Vue.js框架),增加函数接口;
<script>const vue = new Vue({el: '#app',data: {title: '标题1',},});function changeTitle(title) {vue.title = title;}
</script>
  1. 编写C#代码,请注意两处中文注释的部分;
using CefSharp;
using CefSharp.WinForms;
using System;
using System.IO;
using System.Windows.Forms;namespace WindowsFormsApp8 {public partial class Form1 : Form {ChromiumWebBrowser browser;public void InitBrowser() {CefSettings settings = new CefSettings();// Note that if you get an error or a white screen, you may be doing something wrong !// Try to load a local file that you're sure that exists and give the complete path instead to test// for example, replace page with a direct path instead :// String page = @"C:\Users\SDkCarlos\Desktop\afolder\index.html";// String page = string.Format(@"{0}\html-resources\html\index.html", Application.StartupPath);String url = string.Format(@"{0}\ui\test.html", Application.StartupPath);if (!File.Exists(url)) {MessageBox.Show("Error: File doesn't exists : " + url);}// Initialize cef with the provided settingsCef.Initialize(settings);// Create a browser componentbrowser = new ChromiumWebBrowser(url);// Add it to the form and fill it to the form window.this.Controls.Add(browser);browser.Dock = DockStyle.Fill;// Allow the use of local resources in the browserBrowserSettings browserSettings = new BrowserSettings();browserSettings.FileAccessFromFileUrls = CefState.Enabled;browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;browser.BrowserSettings = browserSettings;// 当页面加载完毕时,执行JavaScript代码browser.ExecuteScriptAsyncWhenPageLoaded("changeTitle('我不是鸭鸭')");}public Form1() {InitializeComponent();InitBrowser();}private void button1_Click(object sender, EventArgs e) {// 当点击按钮时,执行JavaScript代码browser.ExecuteScriptAsync("changeTitle('我是鸭鸭')");}}
}
  1. 调试程序,查看效果。

如果需要执行JavaScript代码并得到返回值,代码可以这么编写:
注意:EvaluateScriptAsync()方法是同步执行的,也就是程序会阻塞!

private void button1_Click(object sender, EventArgs e) {// 当点击按钮时,执行JavaScript代码Task<JavascriptResponse> response = browser.EvaluateScriptAsync("add(1, 2)");// response.Result.Result是Object类型MessageBox.Show("返回值为:" + response.Result.Result);
}

JavaScript代码:

function add(a, b) {for (var i = 0; i < 9999999999; ++i) {;}return a + b;
}

6. 在JS中调用C#方法

在C#中编写如下代码:(注意中文注释的部分)
以下是同步执行的演示,即JS会阻塞等待C#执行完再继续执行。

using CefSharp;
using CefSharp.WinForms;
using System;
using System.IO;
using System.Windows.Forms;namespace WindowsFormsApp8 {public partial class Form1 : Form {ChromiumWebBrowser browser;// 创建一个类,用于在JS中访问public class JsEvent {public void SayHello() {MessageBox.Show("你好,C#!");}}public void InitBrowser() {CefSettings settings = new CefSettings();// Note that if you get an error or a white screen, you may be doing something wrong !// Try to load a local file that you're sure that exists and give the complete path instead to test// for example, replace page with a direct path instead :// String page = @"C:\Users\SDkCarlos\Desktop\afolder\index.html";// String page = string.Format(@"{0}\html-resources\html\index.html", Application.StartupPath);String url = string.Format(@"{0}\ui\test.html", Application.StartupPath);if (!File.Exists(url)) {MessageBox.Show("Error: File doesn't exists : " + url);}// Initialize cef with the provided settingsCef.Initialize(settings);// Create a browser componentbrowser = new ChromiumWebBrowser(url);// Add it to the form and fill it to the form window.this.Controls.Add(browser);browser.Dock = DockStyle.Fill;// Allow the use of local resources in the browserBrowserSettings browserSettings = new BrowserSettings();browserSettings.FileAccessFromFileUrls = CefState.Enabled;browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;browser.BrowserSettings = browserSettings;// 绑定JavaScript对象CefSharpSettings.LegacyJavascriptBindingEnabled = true;CefSharpSettings.WcfEnabled = true;BindingOptions bindingOptions = new BindingOptions();// 如果不加此句,那么绑定的方法不能以大写字母开头bindingOptions.CamelCaseJavascriptNames = false;browser.JavascriptObjectRepository.Register("jsObj", new JsEvent(), isAsync: false, options: bindingOptions);}public Form1() {InitializeComponent();InitBrowser();}}
}

在HTML中编写如下代码:

<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>Title</title><link href="./index.css" rel="stylesheet"><script src="./vue.min.js"></script><script src="./index.js"></script>
</head>
<body><div id="app"><el-card class="box-card"><div slot="header" class="clearfix"><span>{{ title }}</span><el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button></div><div v-for="o in 4" :key="o" class="text item">{{ '列表内容 ' + o }}</div></el-card><el-button @click="onclick">触发</el-button>
</div><script>const vue = new Vue({el: '#app',data: {title: '标题1',},methods: {onclick: function () {jsObj.sayHello();console.log('调用完毕!');}},});
</script></body>
</html>

运行效果:

CefSharp 知道这些就完事了相关推荐

  1. C# WPF使用CefSharp客户端内嵌浏览器做一个开小差工具

    前言 CefSharp是一个C#客户端内嵌入chromium开源项目浏览器的工具,方便在客户端中自然的访问网页内容,十分好用.当然,网上有很多使用CefSharp的教程了,怎么使用都很详尽.我这里只是 ...

  2. Winform下CefSharp的引用、配置、实例与报错排除(源码)

    Winform下CefSharp的引用.配置.实例与报错排除 本文详细介绍了CefSharp在vs2013..net4.0环境下,创建Winfrom项目.引用CefSharp的方法,演示了winfro ...

  3. cefsharp已停止工作_Winform下CefSharp的引用、配置、实例与报错排除(源码)

    Winform下CefSharp的引用.配置.实例与报错排除(源码) Winform 下 CefSharp 的引用, 配置, 实例与报错排除 [TOC] 1, 关于 CefSharp 装一手, 比较简 ...

  4. CefSharp 提示 flash player is out of date 运行此插件 等问题解决办法

    CefSharp 提示 flash player is out of date 或者 需要手动右键点 运行此插件 脚本 等问题解决办法 因为中国版FlashPlayer变得Ad模式之后,只好用旧版本的 ...

  5. 使用CEfSharp之旅(7)CEFSharp 拦截 http 请求 websocket 内容

    使用CEfSharp之旅(7)CEFSharp 拦截 http 请求 websocket 内容 原文:使用CEfSharp之旅(7)CEFSharp 拦截 http 请求 websocket 内容 版 ...

  6. Cefsharp生成的项目在自己电脑上能打开,其他电脑上不行,提示找不到指定文件cefsharp.core.dll

    在自己电脑上生成的项目都能打开,但是在别的电脑上打开就提示,找不到指定文件cefsharp.core.dll 有两种原因 一种是dll没有复制过去,复制整个文件夹的文件过去就行 还有一种情况是目标计算 ...

  7. winform利用CefSharp调用google浏览器内核ChromiumWebBrowser,与JS交互

    一开始用了自带的webbrowser,不支持H5,脚本会有问题,后来又用了webkitBrowser,发现有些js效果还是显示不出来,和webbrowser稍微好一点,但是还是不行,然后决定用CefS ...

  8. cefsharp wpf 中文输入问题解决方法

    摘要 最近在搞一个客户端的项目,考虑使用wpf,内嵌webView的方式,访问h5页面.所以使用了CefSharp组件,但发现一个问题,就是在输入中文的时候,无法输入. 解决办法 去官方github的 ...

  9. 使用CEfSharp之旅(1) 加载网络页面

    使用CEfSharp之旅(1) 加载网络页面 原文:使用CEfSharp之旅(1) 加载网络页面 版权声明:本文为博主原创文章,未经博主允许不得转载.可点击关注博主 ,不明白的进群191065815 ...

  10. wpf cefsharp html源码,CefSharp For WPF基本使用

    Nuget引用CefSharp.WpfCefSharp.Commoncef.redist.x64cef.redist.x86 直接搜索安装CefSharp.Wpf即可,因为CefSharp.Wpf依赖 ...

最新文章

  1. VS2008+Windows DDK 7的环境配置(二)
  2. Java多线程的实现方式-Thread 类,Runnable 接口
  3. python:字典的操作
  4. 基于 KubeVela 的 GitOps 交付
  5. u盘数据恢复的原理_日臻薄技 | 电脑回收站数据恢复的三个方法
  6. 计算机教学中因才施教,浅析高校《大学计算机基础》教学中的因材施教
  7. Winform登录窗体登录仿asp.net验证成功后进入主界面
  8. Qt下继承于QObject创建的线程
  9. 10 条提升 Android 性能的建议
  10. 阿里为什么推崇java_为什么阿里巴巴 Java 开发手册推荐使用 LongAdder,而不是 volatile?...
  11. mysql配置和管理(转载)
  12. iOS (导航条)navBar 透明
  13. 开源阅读书源_【阅读】一款开源的强大的看书软件!amp;超多书源。
  14. 电子计算机一直在响,电脑硬盘一直响个不停怎么解决
  15. 在移动硬盘中安装WIN10
  16. 忘记背后 努力面前 向着标杆直跑!(转)
  17. php7 字符串转数字,strtoupper()
  18. 无线电视服务器主机名,电视服务器主机名怎么填
  19. hy-bridge:一款简洁安全可靠的Hybrid框架
  20. 30. 串联所有单词的子串

热门文章

  1. 加深 | Matlab图像实验操作基础(矩阵,九宫格、噪声处理)
  2. UPS 笔记 (逆变电源 DSP)
  3. 全国地区 mysql表_2017全国省市区数据库-2017全国省市区数据库下载 官方版 - 河东下载站...
  4. c语言程序设计实训的心得,C语言程序设计实习心得体会
  5. C语言学习:原子操作
  6. 计算机共享w7系统文件共享,win7系统怎么共享文件 电脑一键共享文件方法教程...
  7. C-V2X通信架构中,PC5接口和Uu接口的区别是什么?
  8. RapidMiner简单入门教程——入门必看超详细
  9. android QQ好友分享
  10. vulnhub--odin