基于.Net CEF 实现 Vue 等前端技术栈构建 Windows 窗体应用
零、参考资料
1、https://github.com/cefsharp/CefSharp/wiki/Quick-Start-For-MS-.Net-5.0-or-greater
2、https://github.com/cefsharp/CefSharp/wiki/Quick-Start
3、https://github.com/cefsharp/CefSharp/wiki/General-Usage#javascript-integration
一、安装 Nuget 包
https://www.nuget.org/packages/CefSharp.WinForms
安装 CefSharp.WinForms 包后会显示 Readme.txt,
二、配置项目
<!-- CefWindowsFormsApp.csproj -->
<PropertyGroup Condition="'$(PlatformTarget)' == 'x64'">
<RuntimeIdentifier Condition="'$(RuntimeIdentifier)' == ''">win-x64</RuntimeIdentifier>
<SelfContained Condition="'$(SelfContained)' == ''">false</SelfContained>
</PropertyGroup>
三、加载远程网页示例
使用 ChromiumWebBrowser 加载百度首页,
// Form1.cs
using CefSharp;
using CefSharp.WinForms;
using System.Windows.Forms;
namespace CefWindowsFormsApp
{
public partial class Form1 : Form
{
private static ChromiumWebBrowser browser;
public Form1()
{
InitializeComponent();
AddChromiumWebBrowser();
}
/// <summary>
/// Create a new instance in code or add via the designer
/// </summary>
private void AddChromiumWebBrowser()
{
browser = new ChromiumWebBrowser("www.baidu.com");
this.Controls.Add(browser);
}
private void Form1_Load(object sender, System.EventArgs e)
{
// Load a url
browser.LoadUrl("https://www.baidu.com/");
}
}
}
这这个示例中,我们引入了 CefSharp 库,在 Form1 窗体中添加了浏览器控件 ChromiumWebBrowser ,并且在窗体启动时加载百度首页,
四、加载本地网页示例
首先创建一个 Vue 项目,
# 使用 Vite
cnpm create vite@latest
# cd vite-project
# cnpm i
接着完成前端的开发之后,打包静态资源,
npm run build
然后在 WinForm 项目下创建 Resources 文件夹,把前端打包的 dist 文件夹下的文件全部复制过来,并且文件属性设置为“嵌入的资源”,
最后通过 RegisterScheme 注册为本地资源访问,
// Form1.cs
using CefSharp;
using CefSharp.SchemeHandler;
using CefSharp.WinForms;
using System.Windows.Forms;
namespace CefWindowsFormsApp
{
public partial class Form1 : Form
{
private static ChromiumWebBrowser browser;
public Form1()
{
InitializeComponent();
AddChromiumWebBrowser();
}
/// <summary>
/// Create a new instance in code or add via the designer
/// </summary>
private void AddChromiumWebBrowser()
{
InitBrowser();
browser = new ChromiumWebBrowser("http://cefsharp.test");
this.Controls.Add(browser);
}
public static void InitBrowser()
{
// Pseudo code; you probably need more in your CefSettings also.
var settings = new CefSettings();
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = "http",
DomainName = "cefsharp.test",
SchemeHandlerFactory = new FolderSchemeHandlerFactory(rootFolder: @"..\..\..\..\CefWindowsFormsApp\Resources",
hostName: "cefsharp.test", //Optional param no hostname/domain checking if null
defaultPage: "index.html") //Optional param will default to index.html
});
Cef.Initialize(settings);
}
private void Form1_Load