WinForm将CefSharp文件放置到程序单独的目录

背景

项目中引用CefSharp类库,将会有一堆的文件需要放置到bin\debug目录下,有强迫症的开发者希望将CefSharp的文件单独放到一个目录下,这样程序文件将会看起来比较整洁。

方法

1.将CefSharp的文件,复制到bin\Debug\resources\cefsharp_x86,,其中resources\cefsharp_x86就是自定义目录。

看上去像这样:


2.项目添加CefSharp类库引用,引用路径就选择bin\Debug\resources\cefsharp_x86下的路径。


3.修改Program.cs文件,写入代码:

using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Forms;
using CefSharp;

namespace CefDemo
{
    internal static class Program
    {
        private static string lib, browser, locales, res;

        /// <summary>
        ///     应用程序的主入口点。
        /// </summary>
        [STAThread]
        private static void Main()
        {
            lib = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"resources\cefsharp_x86\libcef.dll");
            browser = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,@"resources\cefsharp_x86\CefSharp.BrowserSubprocess.exe");
            locales = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"resources\cefsharp_x86\locales\");
            res = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"resources\cefsharp_x86\");

            var libraryLoader = new CefLibraryHandle(lib);
            var isValid = !libraryLoader.IsInvalid;
            if (isValid)
            {
                InitializeCef();
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        /// <summary>
        ///     初始化Cef配置,此方法代码不能放于Main方法中,否则Cef无法正常运行,别问为什么,我也不清楚
        /// </summary>
        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void InitializeCef()
        {
            var settings = new CefSettings
            {
                BrowserSubprocessPath = browser,
                LocalesDirPath = locales,
                ResourcesDirPath = res
            };
            Cef.Initialize(settings, false, false);
        }
    }
}

4.因为在Program.cs文件中初始化好了CefSharp,在其他窗体直接用浏览器控件就可以了。

using System;
using System.Windows.Forms;
using CefSharp.WinForms;

namespace CefDemo
{
    public partial class Form1 : Form
    {
        private ChromiumWebBrowser _browser;

        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            _browser = new ChromiumWebBrowser("http://www.baidu.com");
            Controls.Add(_browser);
            _browser.Dock = DockStyle.Fill;
        }
    }
}

运行效果


注意事项

1.CefSharp框架下载地址:

2.使用.NET 4.5.2或以上版本(vs2010最高支持.NET 4.0,我使用的是vs2017)。

3.在解决方案上右键->"属性"->"生成"->"目标平台",选择x86或x64,Cef暂不支持"Any CPU"

源码下载

https://download.csdn.net/download/a497785609/10476492

参考资料

https://stackoverflow.com/questions/39400139/how-to-move-cefsharp-dependencies-and-files-to-subdirectory


猜你喜欢

转载自blog.csdn.net/a497785609/article/details/80678787