大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。
Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺
参考:https://github.com/cefsharp/CefSharp/issues/601
https://gist.github.com/BlackBooth/19ce027c4f68c1eb4fc1144988ca6662
关键点:
(1)设置CefSettings的BrowserSubprocessPath属性为对应的CefSharp.BrowserSubprocess.exe的路径;
(2)在Program.cs中加载相关程序集;
-
将Cefsharp相关库放到bin\Debug\cefLib目录中
-
添加CefSharp类库引用,并把相关库的属性(复制本地)设置为false,这样VS就不会自动复制相关库到运行目录下;
-
修改Program.cs的代码如下, 注:在Program.cs中不能引用相关的Cefsharp相关库,否则会加载Cefsharp程序集失败;
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
CefSettingClass.InitializeCefSetting();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
//解析程序集失败,会加载对应的程序集
private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
{
Assembly executingAssembly = Assembly.GetExecutingAssembly();
AssemblyName assemblyName = new AssemblyName(args.Name);
var assemblyAllName = assemblyName.Name + ".dll";
//加载CefSharp相关库
if (args.Name.StartsWith("CefSharp"))
{
string assemblyPath = Path.Combine(Application.StartupPath, CefSettingClass.CefLibName, assemblyAllName);
return File.Exists(assemblyPath) ? Assembly.LoadFile(assemblyPath) : null;
}
//判断程序集的区域性
if (!assemblyName.CultureInfo.Equals(CultureInfo.InvariantCulture))
{
assemblyAllName = string.Format(@"{0}\{1}", assemblyName.CultureInfo, assemblyAllName);
}
using (Stream stream = executingAssembly.GetManifestResourceStream(assemblyAllName))
{
if (stream == null) return null;
var assemblyRawBytes = new byte[stream.Length];
stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
return Assembly.Load(assemblyRawBytes);
}
}
}
- 新增CefSettingClass类,用于初始化CefSharp;
class CefSettingClass
{
public const string CefLibName = "cefLib"; //cef目录名称
/// <summary>
/// 初始化CEF的配置
/// </summary>
public static void InitializeCefSetting()
{
string appPath = Application.StartupPath;
CefSettings settings = new CefSettings
{
Locale = "zh-CN", //中文
BrowserSubprocessPath = Path.Combine(appPath, CefLibName, "CefSharp.BrowserSubprocess.exe"), //设置浏览器子程序启动路径
};
Cef.Initialize(settings);
}
}
- 主窗口代码如下,初始化并添加浏览器控件到主窗口中:
public partial class MainForm : Form
{
private ChromiumWebBrowser browser;
public MainForm()
{
InitializeComponent();
}
private void MainForm_Load(object sender, EventArgs e)
{
browser = new ChromiumWebBrowser("https://www.baidu.com")
{
Dock = DockStyle.Fill
};
this.Controls.Add(browser);
this.Closing += OnClosing;
}
private void OnClosing(object sender, CancelEventArgs e)
{
Cef.Shutdown();
}
}
- 最终的程序运行目录和运行结果如下:
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/191957.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...