提示:CefSharp自5.2版本开始就支持AnyCpu,CefSharp需要安装的版本可对照自己.net版本安装。对照网址:GitHub - cefsharp/CefSharp: .NET (WPF and Windows Forms) bindings for the Chromium Embedded Frameworkhttps://github.com/cefsharp/CefSharp
推荐vs2015以上
一、首先安装CefSharp.WinForms,如下图:
二、安装CefSharp.Common,安装此包后会自动安装cef.redist.x64和cef.redist.x86,如果没有请手动安装。
以上的包都必须得装。
三、主要代码,下
面的代码只能执行一次,多次执行会报错。所以可放在program中。
先修改csproj文件
<PropertyGroup>
<CefSharpAnyCpuSupport>true</CefSharpAnyCpuSupport>
</PropertyGroup>
然后在program中添加此代码,也不是必须放在这里。只需要确保此代码在同一个线程中只能执行一次,随便放在哪里均可。
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
#region 加载chrome浏览器,只需要加此部分代码
AppDomain.CurrentDomain.AssemblyResolve += Resolver;
LoadApp();
#endregion
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new srLogin());
}
private static void LoadApp()
{// 构建 x86 或 x64 子目录的路径
string architecture = Environment.Is64BitProcess ? "x64" : "x86";
string browserSubprocessPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, architecture, "CefSharp.BrowserSubprocess.exe");
CefSettings settings = new CefSettings
{
Locale = "zh-CN",
BrowserSubprocessPath = browserSubprocessPath
};
Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);
}
// Will attempt to load missing assembly from either x86 or x64 subdir
private static Assembly Resolver(object sender, ResolveEventArgs args)
{
if (args.Name.StartsWith("CefSharp"))
{
string assemblyName = args.Name.Split(new[] { ',' }, 2)[0] + ".dll";
string archSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
Environment.Is64BitProcess ? "x64" : "x86",
assemblyName);
return File.Exists(archSpecificPath)
? Assembly.LoadFile(archSpecificPath)
: null;
}
return null;
}
四、控件使用
在Nuget中安装包之后,工具箱中会出现Cefsharp的控件ChromiumWebBrowser。直接拖入自己的窗体中即可。如下图:
添加好窗体,使用控件的Load属性即可设置访问的路径。chromiumWebBrowser.Load(url);
特殊情况:运行时若报错,找不到文件则需要将debug文件下面的x86和x64两个文件夹复制到项目跟目录下,属性中需要选择嵌入,发布后运行时才可以找到文件。
注:转载请注明出处。