使用WinFrom + CefSharp 开发客户端程序

今天使用CefSharp,加上本地资源文件嵌入了HTML、CSS、JS文件,做为Winform的UI;效果不错,漂亮可控,简简单单,半天时间搞定从开发到上线;

下面记录下相关的备忘:

 (窗口的效果)

使用WinFrom + CefSharp 开发客户端程序

关闭按钮和最小化按钮,使用JS交互调WIN窗口实现;

重点讲资源文件的嵌入:

1、直接向Resorces文件夹添加文件或文件夹;添加完毕后,每个文件属性需要选择为“嵌入的资源”,才会随程序编译一并打包进程序中;

2、关键的解析:

var ns = ass.GetManifestResourceNames();

 通过这个语句,可以在调试中查看到所有资源的路径;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using CefSharp;

namespace mssClient.Helper
{
    /// <summary>
    /// https://qwqaq.com/ee43a4af.html
    /// </summary>
    public class ResourceSchemeHandler:CefSharp.ResourceHandler
    {
        public override bool ProcessRequestAsync(IRequest request, ICallback callback)
        {
            var names = this.GetType().Assembly.GetManifestResourceNames();

            Console.WriteLine(names);

            Uri u = new Uri(request.Url);
            String file = u.Authority + u.AbsolutePath; // 注:目录名需全为小写字母,否则将无法得到 Resource

            Assembly ass = Assembly.GetExecutingAssembly();
            String resourcePath = ass.GetName().Name + ".Resources." + file.Replace("/", "."); // 你可以设置断点看看这里的值
            var ns = ass.GetManifestResourceNames();
            Task.Run(() =>
            {
                using (callback)
                {
                    if (ass.GetManifestResourceInfo(resourcePath) != null)
                    {
                        Stream stream = ass.GetManifestResourceStream(resourcePath);
                        string mimeType = "application/octet-stream";
                        switch (Path.GetExtension(file))
                        {
                            case ".html":
                                mimeType = "text/html";
                                break;
                            case ".js":
                                mimeType = "text/javascript";
                                break;
                            case ".css":
                                mimeType = "text/css";
                                break;
                            case ".png":
                                mimeType = "image/png";
                                break;
                            case ".appcache":
                                break;
                            case ".manifest":
                                mimeType = "text/cache-manifest";
                                break;
                        }
                        // Reset the stream position to 0 so the stream can be copied into the underlying unmanaged buffer
                        stream.Position = 0;
                        // Populate the response values - No longer need to implement GetResponseHeaders (unless you need to perform a redirect)
                        ResponseLength = stream.Length;
                        MimeType = mimeType;
                        StatusCode = (int)HttpStatusCode.OK;
                        Stream = stream;
                        callback.Continue();
                    }
                    else
                    {
                        callback.Cancel();
                    }
                }
            });

            return true;
        }
    }
}

  下面是协议注册类,写在 Program.cs 中,包含协议注册、CEF初始化代码等;

                //CEF
                try
                {
                    CefSettings settings = new CefSettings();

                    //设置浏览器的UA,将用户等信息放到这里,事实上,Winform应该是先启动登录窗口,登录成功后再隐藏登录窗口并显示主窗口。
                    //settings.UserAgent = "Mss Application Client;";

                    //设置语言环境为中文环境
                    settings.Locale = "zh-CN";

                    //禁用日志输出
                    settings.LogFile = AppDomain.CurrentDomain.BaseDirectory + "Logs\\chromeWebBrowserDebug.log";
                    settings.LogSeverity = LogSeverity.Disable;

                    //注册自定义协议,用于读取exe中的资源文件
                    settings.RegisterScheme(new CefCustomScheme()
                    {
                        SchemeName = CustomSchemeHandler.SchemeName,
                        SchemeHandlerFactory = new CustomSchemeHandler(),
                        IsCorsEnabled = true,
                        IsSecure = false
                    });

                    //注册自定义协议,用于读取本地程序根目录下的文件
                    settings.RegisterScheme(new CefCustomScheme()
                    {
                        SchemeName = LocalScremeHandler.SchemeName,
                        SchemeHandlerFactory = new LocalScremeHandler(),
                        IsCorsEnabled = true,
                        IsSecure = false
                    });

                    //定义缓存目录,不然发布后可能会自动在桌面创建缓存目录
                    settings.CachePath = App.Instance.ChromeCacheDirectory; //AppDomain.CurrentDomain.BaseDirectory + "ChromeCache\\";

                    //Initialize cef with the provided settings
                    Cef.Initialize(settings);

                    //必须做下面的设置,减少白屏的发生,这是CEFSHARP的BUG
                    if (!settings.MultiThreadedMessageLoop)
                    {
                        Application.Idle += (sender, e) => { Cef.DoMessageLoopWork(); };
                    }

                    //必须使用该语句,在显示页面缩放时,启用高DPI缩放支持,否则页面会出现模糊化。事实上就是强制必须使用100%
                    Cef.EnableHighDPISupport();
                }
                catch (Exception ex) { }
                //注册主窗口
                Application.Run(App.Instance.WebLoginForm);

  

使用WinFrom + CefSharp 开发客户端程序

上一篇:delphi DLL image 动态绘图 句柄处理


下一篇:使用rsync备份Windows事件日志