介绍
CEF是由Marshall Greenblatt于2008年创建的基于Google Chromium的BSD许可开源项目。与主要关注谷歌Chrome应用程序开发的Chromium项目本身不同,CEF专注于在第三方应用程序中促进嵌入式浏览器用例。CEF通过提供生产质量稳定的API,发布跟踪特定Chromium版本和二进制发行版的分支机构,使用户免受基础Chromium和Blink代码复杂性的影响。CEF中的大多数功能都具有默认实现,这些实现提供丰富的功能,同时几乎不需要用户进行集成工作。目前,全球已有超过1亿个CEF安装实例嵌入到来自各种公司和行业的产品中。CEF维基百科页面上提供了使用CEF的公司和产品的部分列表。CEF的一些用例包括:
CEF支持各种编程语言和操作系统,可以轻松集成到新的和现有的应用程序中。它从头开始设计,兼顾性能和易用性。基础框架包括通过本机库公开的C和C ++编程接口,这些接口将主机应用程序与Chromium和Blink实现细节隔离开来。它提供了浏览器和主机应用程序之间的紧密集成,包括对自定义插件,协议,JavaScript对象和JavaScript扩展的支持。主机应用程序可以选择控制资源加载,导航,上下文菜单,打印等,同时利用Google Chrome Web浏览器中提供的相同性能和HTML5技术。
前言
有时我们在winform与wpf中嵌入浏览器,需要在页面上读取电脑上的一些信息,这个时候就需要用到CefSharp的RegisterJsObject进行注册方法然后供js进行调用了。
简单实例
我们在winform中嵌入的页面中,显示电脑的信息,电脑信息通过winform进行读取,js调用获取电脑信息的方法,并将最终结果以json字符串的形式传递到js端,js获取到这些信息并在页面上进行显示。
定义一个专门处理js回调的类ScriptCallbackManager
/// <summary>
/// js c#回调类
/// </summary>
class ScriptCallbackManager
{
/// <summary>
/// 查找电脑信息
/// </summary>
/// <param name="javascriptCallback"></param>
public void FindComputerInfo(IJavascriptCallback javascriptCallback)
{
Task.Factory.StartNew(async () =>
{
using (javascriptCallback)
{
Computer computer = new Computer();
string response = JsonConvert.SerializeObject(new
{
cpu_id = computer.CPU_Id,
disk_id = computer.Disk_Id,
host_name = computer.HostName,
networkcard = computer.NetworkCard,
serialNumber = computer.SerialNumber_Manufacturer_Product.Item1,
manufacturer = computer.SerialNumber_Manufacturer_Product.Item2,
product = computer.SerialNumber_Manufacturer_Product.Item3,
});
await javascriptCallback.ExecuteAsync(response);
}
});
}
}
创建一个computer类为获取电脑信息的操作类
/// <summary>
/// 电脑信息类
/// </summary>
public class Computer
{
/// <summary>
/// 查找cpu的id
/// </summary>
/// <returns></returns>
public string CPU_Id
{
get
{
try
{
string str = string.Empty;
ManagementClass mcCPU = new ManagementClass("win32_Processor");
ManagementObjectCollection mocCPU = mcCPU.GetInstances();
foreach (ManagementObject m in mocCPU)
{
str = m["Processorid"].ToString().Trim().Substring(0, 8);
break;
}
return str;
}
catch (Exception)
{
return string.Empty;
}
}
}
public string Disk_Id
{
get
{
try
{
string hdId = string.Empty;
ManagementClass hardDisk = new ManagementClass("win32_DiskDrive");
ManagementObjectCollection hardDiskC = hardDisk.GetInstances();
foreach (ManagementObject m in hardDiskC)
{
hdId = m.Properties["Model"].Value.ToString();//WDC WD800BB-56JKC0
break;
}
return hdId;
}
catch (Exception)
{
return string.Empty;
}
}
}
/// <summary>
/// 网卡
/// </summary>
public string NetworkCard
{
get
{
try
{
string MoAddress = string.Empty;
ManagementClass networkAdapter = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection adapterC = networkAdapter.GetInstances();
foreach (ManagementObject m in adapterC)
{
if ((bool)m["IPEnabled"] == true)
{
MoAddress = m["MacAddress"].ToString().Trim();
m.Dispose();
}
}
return MoAddress;
}
catch
{
return string.Empty;
}
}
}
/// <summary>
/// 获取序列号,制造商,型号
/// </summary>
public Tuple<string, string, string> SerialNumber_Manufacturer_Product
{
get
{
try
{
Tuple<string, string, string> tuple = null; new Tuple<string, string, string>(string.Empty,
string.Empty, string.Empty);
ManagementObjectSearcher mos = new ManagementObjectSearcher("select * from Win32_baseboard");
foreach (ManagementObject m in mos.Get())
{
tuple = new Tuple<string, string, string>(m["SerialNumber"].ToString(), m["Manufacturer"].ToString(),
m["Product"].ToString());
}
return tuple;
}
catch (Exception)
{
return null;
}
}
}
/// <summary>
/// 计算机名称
/// </summary>
public string HostName
{
get
{
return System.Net.Dns.GetHostName();
}
}
}
嵌入web页面
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery.min.js"></script>
<script>
//设置电脑信息
function callback(data) {
data = JSON.parse(data);
$("#msg").html('');
$("#msg")
.append($("<li>cpu_id:" + data.cpu_id + "</li>"))
.append($("<li>disk_id:" + data.disk_id + "</li>"))
.append($("<li>host_name:" + data.host_name + "</li>"))
.append($("<li>networkcard:" + data.networkcard + "</li>"))
.append($("<li>serialNumber:" + data.serialNumber + "</li>"))
.append($("<li>manufacturer:" + data.manufacturer + "</li>"))
.append($("<li>product:" + data.product + "</li>"));
};
function findComputerInfo() {
//调用后台C#FindComputerInfo,返回结果回调方法callback
googleBrower.FindComputerInfo(callback);
};
</script>
</head>
<body>
<button onclick="findComputerInfo()">获取电脑信息</button>
<ul id="msg"></ul>
</body>
</html>
单击按钮,在Web页面上显示当前电脑信息
winform窗体代码
/// <summary>
/// 主窗体
/// </summary>
public partial class MainFrm : Form
{
private CefSharp.CefSettings _settings;
CefSharp.WinForms.ChromiumWebBrowser _webView;
public MainFrm()
{
InitializeComponent();
_settings = new CefSharp.CefSettings();
CefSharp.Cef.Initialize(_settings);
this.FormClosed += MainFrm_FormClosed;
}
void MainFrm_FormClosed(object sender, FormClosedEventArgs e)
{
if (_webView != null)
{
_webView.Dispose();
}
}
private void MainFrm_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
string url = "file:///E:/xxx/bin/x64/Debug/lenovo/test.html";
LoadPage(url);
}
/// <summary>
/// 加载页面
/// </summary>
/// <param name="url"></param>
private void LoadPage(string url)
{
if (_webView == null)
{
_webView = new CefSharp.WinForms.ChromiumWebBrowser(url);
_webView.Dock = DockStyle.Fill;
_webView.LifeSpanHandler = new OpenPageSelf();
_webView.RegisterJsObject("googleBrower", new ScriptCallbackManager(),
new CefSharp.BindingOptions { CamelCaseJavascriptNames = false });
this.Controls.Add(_webView);
}
else
{
_webView.Load(url);
}
}
}
本文转载于博客园
原文链接:
https://www.cnblogs.com/zengzhanping/p/10646892.html?tdsourcetag=s_pcqq_aiomsg
作者:无赖痞子