环境:
.net 4.5.2
cefsharp版本 86.0.24.1
winform
参考以下文章,不能生效,检查了一下,更新了某些配置,有所改动,能够生效。
************************
https://blog.csdn.net/xiezhongyuan07/article/details/84402083 cefsharp的cefsetting结构的属性讲解
https://blog.csdn.net/a497785609/article/details/80678787 cefsharp移动到其他文件夹的另一篇文章
************************
以下是原文:
参考: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();
}
}
- 最终的程序运行目录和运行结果如下: