前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >winform与cefsharp混合开发_winform窗体

winform与cefsharp混合开发_winform窗体

作者头像
全栈程序员站长
发布2022-11-05 10:36:28
2.7K0
发布2022-11-05 10:36:28
举报

大家好,又见面了,我是你们的朋友全栈君。

简介

CefSharp简单来说就是一款.Net编写的浏览器包,方便你在Winform和WPF中内嵌的Chrome浏览器组件。

资源

GitHub地址:传送门 wiki帮助文档地址:传送门 CefSharp最小的示例工程:传送门 gitter交流讨论区:传送门

快速入门

本文使用版本cefsharp/71

要求

安装

这块安装使用没有想象的那么简单,比较坑爹,各种修改配置,按照官网的A配置方案没有搞定,按照B配置方案勉强部署成功(VS2013/VS2017)!对于外文不好的我,看着英文文档脑壳疼。老外给的闭坑指南,但是感觉没有啥卵用。下面就介绍一下B方案安装部署的过程吧,A方案我就不讲了,想看的请去上面的官网查看。

简略测试部署过程

整个工程可在GitHub下载:传送门

  • 创建工程Test.App(Winform工程),将其中的Form1窗体删掉。
  • 创建工程Test.Chrome(类库)。
  • 在Test.Chrome工程添加NuGet引用,搜索CefSharp,选择CefSharp.Winforms。
  • 在解决方案上点配置管理器,将平台设置为x86或x64.
  • 在Test.Chrome工程添加Form1窗体,添加CefSharp窗体相关的代码。
  • Test.App添加Test.Chrome工程的引用,修改Program.cs文件,引用Test.Chrome工程的Form1窗体。

部署过程细节截图
  1. 创建一个基础的Winform应用,并使用NuGet引用CefSharp包。使用Nuget添加引用,搜索CefSharp,添加CefSharp.WinForm,CefSharp.Winform依赖好几个包,这块选择这一个安装就可以了,NuGet会自动帮你把其他依赖的包一并下载好的。
在这里插入图片描述
在这里插入图片描述

安装完你本地的Packages文件夹里有如下文件:

在这里插入图片描述
在这里插入图片描述

官方文档建议:安装完NuGet包之后,关闭vs然后重新打开,避免VS自带的智能感知引用有问题

在这里插入图片描述
在这里插入图片描述
  1. 在简介方案上右键—》选择配置管理—》修改目标平台为x86或x64
在这里插入图片描述
在这里插入图片描述

选择x86或x64

在这里插入图片描述
在这里插入图片描述
  1. 在你的窗体Form1窗体里添加相应代码,参考Using CEF (as Browser)中的代码。

Using CEF (as Browser)

在代码中引用相应的dll

代码语言:javascript
复制
using CefSharp;
using CefSharp.WinForms;

完整示例:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;

namespace embebbedChromium
{
    public partial class Form1 : Form
    {
        public ChromiumWebBrowser chromeBrowser;
 
        public Form1()
        {
            InitializeComponent();
            // Start the browser after initialize global component
            InitializeChromium();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

		//初始化浏览器并启动
        public void InitializeChromium()
        {
            CefSettings settings = new CefSettings();
            // Initialize cef with the provided settings
            Cef.Initialize(settings);
            // Create a browser component
            chromeBrowser = new ChromiumWebBrowser("https://www.baidu.com");
            // Add it to the form and fill it to the form window.
            this.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill;
        }
		
		//窗体关闭时,记得停止浏览器
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }        
    }
}
在这里插入图片描述
在这里插入图片描述

3.2. Using CEF (as User Interface)

这块参考官方文档:传送门,做了部分内容的完善,这块我理解的就是提供了一个js调用C#类方法的一个示例。

下载Bootstrap相关的文件,传送门

在这里插入图片描述
在这里插入图片描述

将下载好的Bootstrap文件夹复制拷贝到你的VS项目中,并添加html文件夹,在里面新建一个index.html文件,具体如下图所示:

在这里插入图片描述
在这里插入图片描述

html文件内容参考这里:传送门,网页下方有示例,也有模板可以下载。

代码语言:javascript
复制
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Bootstrap 101 Template</title>

    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
  </head>
  <body>
    <h1>Hello, world!</h1>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.proxy.ustclug.org/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

将上面的css、fonts、html、js文件夹里的文件全部选中—》然后点击鼠标右键,选中属性—》设置始终复制

新建一个类CefCustomObject,用来让js调用C#中类的方法,具体代码如下:

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.Diagnostics;

namespace embebbedChromium
{
    class CefCustomObject
    {
        // Declare a local instance of chromium and the main form in order to execute things from here in the main thread
        private static ChromiumWebBrowser _instanceBrowser = null;
        // The form class needs to be changed according to yours
        private static Form1 _instanceMainForm = null;


        public CefCustomObject(ChromiumWebBrowser originalBrowser, Form1 mainForm)
        {
            _instanceBrowser = originalBrowser;
            _instanceMainForm = mainForm;
        }

        public void showDevTools()
        {
            _instanceBrowser.ShowDevTools();
        }

        public void opencmd()
        {
            ProcessStartInfo start = new ProcessStartInfo("cmd.exe", "/c pause");
            Process.Start(start);
        }
    }
}

修改Form1窗体的代码

代码语言:javascript
复制
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
using System.Runtime.InteropServices;
namespace embebbedChromium
{
public partial class Form1 : Form
{
public ChromiumWebBrowser chromeBrowser;
public Form1()
{
InitializeComponent();
// Start the browser after initialize global component
InitializeChromium();
//需要添加此句代码,否则下面执行会报错
CefSharpSettings.LegacyJavascriptBindingEnabled = true;	            
// Register an object in javascript named "cefCustomObject" with function of the CefCustomObject class :3
chromeBrowser.RegisterJsObject("cefCustomObject", new CefCustomObject(chromeBrowser, this));
}
private void Form1_Load(object sender, EventArgs e)
{
//此句代码执行有错,官网示例的跑不起来
//chromeBrowser.ShowDevTools();
}
public void InitializeChromium()
{
CefSettings settings = new CefSettings();
// Note that if you get an error or a white screen, you may be doing something wrong !
// Try to load a local file that you're sure that exists and give the complete path instead to test
// for example, replace page with a direct path instead :
// String page = @"C:\Users\SDkCarlos\Desktop\afolder\index.html";
String page = string.Format(@"{0}\html-resources\html\index.html", Application.StartupPath);
//String page = @"C:\Users\SDkCarlos\Desktop\artyom-HOMEPAGE\index.html";
if (!File.Exists(page))
{
MessageBox.Show("Error The html file doesn't exists : "+page);
}
// Initialize cef with the provided settings
Cef.Initialize(settings);
// Create a browser component
chromeBrowser = new ChromiumWebBrowser(page);
// Add it to the form and fill it to the form window.
this.Controls.Add(chromeBrowser);
chromeBrowser.Dock = DockStyle.Fill;
// Allow the use of local resources in the browser
BrowserSettings browserSettings = new BrowserSettings();
browserSettings.FileAccessFromFileUrls = CefState.Enabled;
browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
chromeBrowser.BrowserSettings = browserSettings;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Cef.Shutdown();
}
}
}
  1. 运行查看效果,如下图所示
在这里插入图片描述
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/191642.html原文链接:https://javaforall.cn

本文参与?腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年9月19日 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客?前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与?腾讯云自媒体同步曝光计划? ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • 资源
  • 快速入门
    • 要求
      • 安装
        • 简略测试部署过程
        • 部署过程细节截图
      • Using CEF (as Browser)
        • 3.2. Using CEF (as User Interface)
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
        http://www.vxiaotou.com