目录

WPF 程序使用 CefSharp

添加 AnyCPU 支持

  • 需要在项目配置文件的第一个 <PropertyGroup> 节点中添加 <CefSharpAnyCpuSupport>true</CefSharpAnyCpuSupport>

  • WPF 启动时代码如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public partial class App : Application
{
    public App()
    {
        //Add Custom assembly resolver
        AppDomain.CurrentDomain.AssemblyResolve += Resolver;

        //Any CefSharp references have to be in another method with NonInlining
        // attribute so the assembly rolver has time to do it's thing.
        InitializeCefSharp();
    }

    [MethodImpl(MethodImplOptions.NoInlining)]
    private static void InitializeCefSharp()
    {
        var settings = new CefSettings();

        // Set BrowserSubProcessPath based on app bitness at runtime
        settings.BrowserSubprocessPath = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase,
                                               Environment.Is64BitProcess ? "x64" : "x86",
                                               "CefSharp.BrowserSubprocess.exe");

        // Make sure you set performDependencyCheck false
        Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);
    }

    // Will attempt to load missing assembly from either x86 or x64 subdir
    // Required by CefSharp to load the unmanaged dependencies when running using AnyCPU
    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;
    }
}

参考 https://www.shuzhiduo.com/A/n2d9QqgVdD/

win8 参考 https://www.shuzhiduo.com/A/1O5ElwVGJ7/

警告
本文最后更新于 April 8, 2020,文中内容可能已过时,请谨慎使用。