我已经创建了一个带有WPF窗口的类库项目。在一个WPF窗口中,我想获得一个CefSharp浏览器。我的项目应该配置AnyCPU。在不同的教程中,我看到使用CefSharp在可执行项目中调整AnyCPU配置的一点是设置(csproj)
<Prefer32Bit>true</Prefer32Bit>
但是在类库项目中,此属性已禁用。如何在类库中启用CefSharp的AnyCPU支持?
请参阅文档:General Usage Guide
有几种解决方案可以启用AnyCPU支持。我使用了以下内容:
首先,通过NuGet安装依赖项。
然后,将<CefSharpAnyCpuSupport>true</CefSharpAnyCpuSupport>
添加到PropertyGroup
文件的第一个.csproj
中,该文件包含用于CefSharp.Wpf
控件的CefSharp.Wpf.ChromiumWebBrowser
PackageReference。
现在,编写一个Assembly Resolver来根据当前架构找到正确的非托管DLL:
AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve;
private Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.Name.StartsWith("CefSharp"))
{
string assemblyName = args.Name.Split(new[] { ',' }, 2)[0] + ".dll";
string architectureSpecificPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
Environment.Is64BitProcess ? "x64" : "x86",
assemblyName);
return File.Exists(architectureSpecificPath)
? Assembly.LoadFile(architectureSpecificPath)
: null;
}
return null;
}
最后,至少使用以下设置初始化CefSharp:
var settings = new CefSettings()
{
BrowserSubprocessPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
Environment.Is64BitProcess ? "x64" : "x86",
"CefSharp.BrowserSubprocess.exe")
};
Cef.Initialize(settings);