侧边栏壁纸
博主头像
怪客のBlog 博主等级

行动起来,活在当下

  • 累计撰写 36 篇文章
  • 累计创建 1 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录
C#

WinForm下CefSharp使用

怪客
2023-01-17 / 0 评论 / 0 点赞 / 85 阅读 / 0 字

安装依赖包

Install-Package CefSharp.WinForms

初始化CefSharp

            var setting = new CefSettings();
            // 设置语言
            setting.Locale = "zh-CN";
            setting.CefCommandLineArgs.Add("proxy-auto-detect", "0");
            setting.CefCommandLineArgs.Add("no-proxy-server", "1");
            CefSharp.Cef.Initialize(setting);
            CefSharpSettings.WcfEnabled = true;
            CefSharpSettings.ConcurrentTaskExecution = true;
            var Chromium = new ChromiumWebBrowser();
            Chromium.Dock = DockStyle.Fill;
            Chromium.MenuHandler = new MenuHandler();
            Controls.Add(Chromium);

加载网页

            //加载本地html文件和在线网址
            Chromium.Load("D:\\test.html");
            Chromium.LoadUrl("https://www.baidu.com");
            
            //加载html内容字符串
            Chromium.LoadHtml("<h1>测试</h1>");

Js调用C#方法

编写Js调用类

image-1674005984097

注册Js调用对象

            //基本注册
             Chromium.JavascriptObjectRepository.Register(“jsCall”, new JsCall(), isAsync: false, options: BindingOptions.DefaultBinder);
 
            //按需注册(需添加一个自定义特性JsInvokeAttribute,然后在需要Js调用的类上使用)
            WorkContext.Chromium.JavascriptObjectRepository.ResolveObject += (sender, e) =>
            {
                var repo = e.ObjectRepository;
                var objectName = e.ObjectName;
                //反射获取所有Js调用类
                var models = CommonHelper.GetModels("MyWinFormApp.exe", "MyWinFormApp.JsCallModels", t => t.CustomAttributes.Any(c => c.AttributeType.Equals(typeof(JsInvokeAttribute))));

                switch (objectName)
                {
                    case "jsCall":
                        repo.Register(objectName, models.FirstOrDefault(t => t.GetType().Name.ToLower() == objectName.ToLower()), isAsync: true, options: BindingOptions.DefaultBinder);
                        break;
                    default:
                        break;
                }
            };
            
            //批量全部注册
            var models = CommonHelper.GetModels("MyWinFormApp.exe", "MyWinFormApp.JsCallModels", t => t.CustomAttributes.Any(c => c.AttributeType.Equals(typeof(JsInvokeAttribute))));
            foreach (var model in models)
            {
                var modelName = model.GetType().Name;
                modelName = modelName[0].ToString().ToLower() + modelName.Substring(1);
                WorkContext.Chromium.JavascriptObjectRepository.Register(modelName, model, isAsync: false, options: BindingOptions.DefaultBinder);
            }

Js调用

            jsCall.login('admin', '123456');//方法名首字母要小写

C#执行Js代码

无需返回值

Chromium.ExecuteScriptAsync("alert(666);");
Chromium.ExecuteScriptAsyncWhenPageLoaded("alert(666);");

有返回值

var result=Chromium.EvaluateScriptAsync("function test(){return '测试';}test();").Result.Result;

鼠标右键菜单控制

定义一个MenuHandler

    internal class MenuHandler : IContextMenuHandler
    {
        public void OnBeforeContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
        {
            //model.Remove(CefMenuCommand.ViewSource);//移除查看源码选项
            //model.Clear();//清除所有选项(不显示菜单)
        }

        public bool OnContextMenuCommand(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
        {
            return false;
        }

        public void OnContextMenuDismissed(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame)
        {

        }

        public bool RunContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model, IRunContextMenuCallback callback)
        {
            return false;
        }
    }
0

评论区