0


winform使用CefSharp嵌入VUE网页并交互

1、NuGet添加CefSharp

如果下载慢或失败可以更新下载源


腾讯资源https://mirrors.cloud.tencent.com/nuget/华为资源https://repo.huaweicloud.com/repository/nuget/v3/index.json
2、将项目平台改为X64

3、在winform窗体添加cef

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

namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ChromiumWebBrowser browser;
        private void Form1_Load(object sender, EventArgs e)
        {
            if (!Cef.IsInitialized)
            {
                //初始化CEF
                var settings = new CefSettings();
                settings.Locale = "zh-CN";
                CefSharp.Cef.Initialize(settings);
                browser = new ChromiumWebBrowser(AppDomain.CurrentDomain.BaseDirectory + @"\dist\index.html");
                browser.Dock = DockStyle.Fill;
                this.Controls.Add(browser);
                //隐藏右击菜单
                browser.MenuHandler = new ChromMenuHandler();
                //注册对象到JS中,JS与窗体交互
                BoundObject boundObject = new BoundObject();
                browser.JavascriptObjectRepository.Register("csharpObj", boundObject, true);
                //页面加载完事件
                browser.FrameLoadEnd += Browser_FrameLoadEnd;
            }
        }

        private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
        {
            //调用js里的函数
            var data = new {name="张三" };
            var jsetting = new JsonSerializerSettings();
            jsetting.NullValueHandling = NullValueHandling.Ignore;
            string js = "window.SetData(" + JsonConvert.SerializeObject(data, jsetting) + "," + JsonConvert.SerializeObject(data, jsetting) + ")";
            var task =  browser.EvaluateScriptAsync(js);
        }
    }
}

ChromMenuHandler

using CefSharp;

namespace WindowsFormsApp2
{
    /// <summary>
    /// 禁用右击菜单
    /// </summary>
    class ChromMenuHandler : IContextMenuHandler
    {
        public void OnBeforeContextMenu(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
        {
            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;
        }
    }
}

BoundObject

using System;

namespace WindowsFormsApp2
{
    /// <summary>
    /// js调用窗体方法
    /// </summary>
    class BoundObject
    {
        public String test(string data) {
            return "true";
        }
    }
}

4、vue代码编写

<script>
export default {
  data() {
    return {};
  },

  mounted: function () {
    //让窗体可以调用js的函数
    window.SetData = this.SetData;
    //拿到窗体注册的对象
    this.$nextTick(function () {
      this.bindObjectAsync();
    });
  },
  methods: {
      SetData(option, option1) {
      return "拿到数据了";
    },
    test(data){
csharpObj.test(JSON.stringify(data)).then(function (actualResult) {
        //弹出获取到的C#方法返回的参数
        if (actualResult == "true") {

        } else {

        }
      });
},
    async bindObjectAsync() {
      try {
        //名字要与c#里注册的名字一致
        await CefSharp.BindObjectAsync("csharpObj");
        console.info(csharpObj);
      } catch (error) {
        console.warn(error);
      }
    },
  }
}
</script>

5、打包vue并放到项目下并设置复制到输出目录

6、打包vue时去除后缀

vue.config.js

加以下代码

chainWebpack: config => {
        if (process.env.NODE_ENV === 'production') {
            config.output.filename('js/[name].js').end();
            config.output.chunkFilename('js/[name].js').end();
      
            config.plugin('extract-css').tap(args => [{
                filename: `css/[name].css`,
                chunkFilename: `css/[name].css`
            }])
        }
    },

本文转载自: https://blog.csdn.net/qq_34533703/article/details/134974314
版权归原作者 qq_34533703 所有, 如有侵权,请联系我们删除。

“winform使用CefSharp嵌入VUE网页并交互”的评论:

还没有评论