CefSharp 知道这些就完事了

article/2025/11/7 11:38:04

文章目录

  • 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>

运行效果:
在这里插入图片描述


http://chatgpt.dhexx.cn/article/P2IE6MOO.shtml

相关文章

TinyLFU: A Highly Efficient Cache Admission Policy

缓存是计算机科学中可以提高系统性能的最基本、最有效的一种方法之一。当完整的数据不适合全部缓存时&#xff0c;通过将一小部分数据存放到更快、更接近应用程序的内存中来提高性能。缓存可以提高性能的最直观原因在于数据的访问都表现出相当程度的“局部性”。更正式的表征这…

首次接触CefSharp

无疑是我最拿手的开发工作。可是作为一个想成为全能骑士的程序员&#xff0c;当然要能满足各种开发需求。 但是界面这种东西不让我用前端来做心里会很憋屈的。所以在各种需求面前我都会找是否能与HTML混合开发。 我使用过的混合开发平台 C# WebView 追溯到最早我的混合开发还是…

BUUCTF Misc 穿越时空的思念 [ACTF新生赛2020]outguess [HBNIS2018]excel破解 [HBNIS2018]来题中等的吧

目录 穿越时空的思念 [ACTF新生赛2020]outguess [HBNIS2018]excel破解 [HBNIS2018]来题中等的吧 穿越时空的思念 下载文件 使用Audacity打开 点击图示位置&#xff0c;选择分离立体声到单声道&#xff0c;得到一串摩斯&#xff08;右声道&#xff09;&#xff0c;记录下来复…

【buuctf】cscctf_2019_qual_babyheap

buuctf【cscctf_2019_qual_babyheap】 今天找了一道100分题目&#xff0c;题目本身并没有那么难 例行检查 64位的程序&#xff0c;保护机制全开&#xff0c;放到IDA中分析 漏洞分析 函数功能很简单&#xff0c;功能基本齐全&#xff0c;漏洞点在creat()中&#xff0c; 当我…

CE-FPN: Enhancing Channel Information for Object Detection

论文链接: https://arxiv.org/pdf/2103.10643v1.pdf 本文提出了一种新的通道增强特征金字塔网络&#xff08;CE-FPN&#xff09;&#xff0c;具体地说&#xff0c;受亚像素卷积的启发&#xff0c;提出了一种亚像素跳跃融合方法来执行通道增强和上采样。它代替了原来的11卷积和…

CEF一些基本知识

一.CEF简介 Chromium Embedded Framework (CEF)是个基于Google Chromium项目的开源Web browser控件&#xff0c;支持Windows, Linux, Mac平台。 简单说就是Chrome的开源版&#xff0c;目前很多所谓的双核浏览器&#xff0c;实质就是chromeIE的双核。基于HTML5的支持&#xff0c…

CEF环境编译

文章目录 前言龙芯-CEF用户使用手册Tutorial源码入口函数编译步骤最后 前言 Chromium Embedded Framework (CEF) 官方镜像。 一个简单的框架&#xff0c;用于将基于 Chromium 的浏览器嵌入到其他应用程序中。 CEF仓库&#xff1a;chromiumembedded/cef 二进制CEF: CEF Autom…

CEM和BBHE

逆光图像处理 CEMBBHE代码CEMBBHE 今天又了解到了两种对亮度处理的方法。分别是CEM和BBHE。 参考: CEM_matlab. BBHE_matlab. BBHE_C. CEM 单纯的CEM公式比较简单&#xff0c;原理和公式如下 根据网上一个matlab程序复写了一遍python的&#xff0c;灰度图是有效果的。彩色…

模拟生成高斯噪声

之前有做过在图像上加高斯噪声的实验&#xff0c;在模拟生成随机数&#xff0c;以及产生高斯分布噪声时&#xff0c;受到了一些干扰。尤其是和高斯模糊相混淆。对于初学者来说&#xff0c;这些虽然是一些基本的图像处理知识&#xff0c;但是&#xff0c;眼高手低是很要不得的。…

CSS实现高斯模糊效果

用CSS实现高斯模糊效果&#xff1a;filter、backdrop-filter 高斯模糊是一种常见的效果&#xff08;俗称毛玻璃效果&#xff09;&#xff0c;在CSS中使用filter、backdrop-filter属性均可实现 一、filter 这其实是一种“假”模糊&#xff0c;需要一层做背景并使用filter属性达到…

(三)对图像进行Gauss高斯平滑处理

对图像进行Gauss高斯平滑处理 平滑滤波 图像在采集、传输和转换过程中都容易受环境的影响&#xff0c;这在图像中就表现为噪声&#xff0c;这些噪声会致使图像质量降低或者干扰我们提取原本想要的图像信息&#xff0c;所以需要通过滤波技术来去除这些图像中的噪声干扰。 常见…

高斯白噪声(white Gaussian noise,WGN)及matlab演示

原文链接&#xff1a;http://wenku.baidu.com/link?urlmj_wz_9l7PAlURQYi1iOnTnweMxyPvoTWGgoIQdCh2v0Yugt7v_G9QsUkS6Ww-ro2VhJ3L9rsE9kqhqX1V-3TlLNeZdcx_zrLlzZBBIhgqK 文库上看到的一片文章&#xff0c;讲的非常清晰明了&#xff0c;我等渣渣不得不转啊。 本文科普一下高斯…

高斯平滑 高斯模糊 高斯濾波器 ( Gaussian Smoothing, Gaussian Blur, Gaussian Filter ) C++ 實現

http://blog.csdn.net/cay22/article/details/5546636 高斯平滑 高斯模糊 高斯濾波器 ( Gaussian Smoothing, Gaussian Blur, Gaussian Filter ) C 實現 在之前提到過了均值濾波器, 就是說某像素的顏色, 由以其為中心的九宮格的像素平均值來決定. 在這個基礎上又發展成了帶權的…

高斯玻色采样enhance量子近似优化算法

上篇博文&#xff0c;我们已经接触了QAOA量子近似优化算法&#xff0c;我们已经知道近似优化算法一般用于求解组合优化问题。这里我们再说明一下什么是组合优化问题&#xff1a; 给定一个数据集 X &#xff5b; x 1 , x 2 , . . . x N &#xff5d; X&#xff5b;{x_{1},x_{2…

matlab 绘制高斯(Gaussan)函数图像

高斯函数如下&#xff1a; G a u s s a n 1 2 π σ e − ( x − μ ) 2 2 σ 2 Gaussan \frac{1}{\sqrt{2\pi}\sigma}e^{-\frac{(x-\mu)^2}{2\sigma^2}} Gaussan2π ​σ1​e−2σ2(x−μ)2​ 使用 MATLAB 编写高斯函数&#xff0c;需传入 x , μ , σ x,\mu,\sigma x,μ,…

高斯平滑滤波器(Gaussian Smoothing Filter)

一、图像滤波的基本概念 图像常常被强度随机信号&#xff08;也称为噪声&#xff09;所污染。一些常见的噪声有椒盐&#xff08;Salt & Pepper&#xff09;噪声、脉冲噪声、高斯噪声等。椒盐噪声含有随机出现的黑白强度值&#xff0e;而脉冲噪声则只含有随机的白强度值&am…

高斯滤波(Gauss filtering)

1.概念介绍 高斯滤波是一种线性平滑滤波&#xff0c;适用于消除高斯噪声&#xff0c;广泛应用于图像处理的减噪过程。  通俗的讲&#xff0c;高斯滤波就是对整幅图像进行加权平均的过程&#xff0c;每一个像素点的值&#xff0c;都由其本身和邻域内的其他像素值经过加权平均后…

Matlab_用高斯赛德尔(Gaoss-Seidel)迭代法解线性方程组

1.程序代码 function xGauss(A,b,x0,ep,N) %用途&#xff1a;用高斯迭代法解线性方程组Axb %A为系数矩阵&#xff0c;b为右端向量&#xff0c;x0为初始向量&#xff08;默认零向量&#xff09; %ep为精度&#xff08;1e-6&#xff09;&#xff0c;N为最大迭代次数&#xff…

gaussian_filter( )函数(高斯滤波)

对一个数进行高斯滤波&#xff08;模糊&#xff09;可以理解成将该数取附近矩形窗口所有值的加权平均值&#xff0c;距离处理数越近的点权重越大&#xff0c;距离处理点越远的点权重越小。因此如果取的矩形窗口越大&#xff0c;那么对处理点的模糊效果越强烈。 上图&#xff0c…

Gauss-Seidel迭代法的C++实现

高斯赛德尔迭代法大家可以从网站上找到相关的公式推导&#xff0c;这里给出它的C算法实现和运行的结果。 #include<iostream> #include<math.h> using namespace std;int n; //定义全局变量 double a[100…