C#使用WebView2替代Electron


C#想要實現Electron那樣混合桌面程序可以用以下幾個庫.
本文使用EdgeSharp

開始

EdgeSharp可以直接使用HTML,

也可以配合Blazor、Razor 、SolidJs、Svelte、React、Vue、Angular等前端框架。

直接調用系統中Edge瀏覽器所配套的 WebView2,

無需像Electron那樣打包整個瀏覽器內核,打包后的文件非常小。

 

更多強大的功能可以查看官方示例,本文只使用了最簡單的HTML

EdgeSharp.Samples/angular-react-vue

EdgeSharp.Samples/winform

EdgeSharp.Samples/wpf

創建一個Winform程序

創建后,刪除其他文件,只保留 Program.cs

Nuget安裝相關依賴

    <PackageReference Include="EdgeSharp.Core" Version="0.9.0" /> <PackageReference Include="EdgeSharp.WinForms" Version="0.9.0" />

將下面代碼放入Program.cs中

using System.ComponentModel; using System.Windows.Forms; using EdgeSharp.Core; using EdgeSharp.Core.Configuration; using EdgeSharp.Core.Defaults; using EdgeSharp.Core.Infrastructure; using EdgeSharp.WinForms; using HelloEdgeSharp.Controller; using Microsoft.Extensions.DependencyInjection; namespace HelloEdgeSharp { internal static class Program {   [STAThread] static void Main() { try { Application.SetHighDpiMode(System.Windows.Forms.HighDpiMode.SystemAware); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var appBuilder = new AppBuilder<Startup>(); ServiceLocator.Bootstrap(appBuilder); var bowserForm = (BrowserForm)ServiceLocator.Current.GetInstance<IBrowserWindow>(); Application.Run(bowserForm); appBuilder?.Stop(); } catch (Exception e) { MessageBox.Show(e.Message); } } } public class Startup : WinFormsStartup { public override void ConfigureServices(IServiceCollection services) { base.ConfigureServices(services); services.AddSingleton<IConfiguration, SampleConfig>(); services.AddSingleton<IBrowserWindow, SampleBrowserForm>(); // 注入 控制器  RegisterActionControllerAssembly(services, typeof(HelloController).Assembly); } public override void Initialize(IServiceProvider serviceProvider) { base.Initialize(serviceProvider); } } internal class SampleConfig : Configuration { public SampleConfig() : base() { // 攔截 api 並導航到 Controller (用RegisterActionControllerAssembly注冊控制器)  UrlSchemes.Add(new("http", "api", null, UrlSchemeType.ResourceRequest)); // 靜態文件資源 攔截 導航到 wwwroot  UrlSchemes.Add(new("http", "app", "wwwroot", UrlSchemeType.HostToFolder)); // 設置 首頁地址  StartUrl = "http://app/index.html"; ; // 去掉窗口標題欄  //WindowOptions.Borderless = true;  } } internal class SampleBrowserForm : BrowserForm { public SampleBrowserForm() { Width = 1200; Height = 900; var executable = System.Reflection.Assembly.GetExecutingAssembly(); var iconStream = executable.GetManifestResourceStream("EdgeSharp.WinForms.Sample.edgesharp.ico"); if (iconStream != null) { Icon = new Icon(iconStream); } } // 可以重寫 各種生命周期  protected override void Bootstrap() { base.Bootstrap(); } protected override void OnClosing(CancelEventArgs e) { base.OnClosing(e); } } } 

 

新建 Controller/HelloController.cs

繼承 ActionController , 並添加 ActionController , ActionRoute 兩個特性
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EdgeSharp.Core.Network; namespace HelloEdgeSharp.Controller {  [ActionController(Name = "HelloController", Description = "測試控制器")] public class HelloController : ActionController { public class UserInfo { public int Id { get; set; } public string Name { get; set; } public string Version { get; set; } public string Url { get; set; } } public class Result<T> { public bool Succeeded { get; set; } public T Data { get; set; } public string Errors { get; set; } }    [ActionRoute(Path = "/getFrameWorks")] public Result<object> GetFrameWorks(int index, int size) { var list = new List<UserInfo> { new UserInfo() { Id = 1, Name = "React", Version = "v1", Url = "http://www.react.com", }, new UserInfo() { Id = 2, Name = "Vue", Version="v2", Url = "http://www.vue.com", } }; return new Result<object> { Succeeded = true, Data = new { Items = list, TotalCount = 100, } }; } } } 

 

新建 wwwroot/index.html

html代碼省略
這里是Js發起請求與C#交互的關鍵代碼
// 在C# SampleConfig 中配置了UrlSchemeType.ResourceRequest, // 會攔截這個域名 http://api/ 的請求 let instance = axios.create({ baseURL: "http://api/", timeout: 15000, }); // 發起get請求 instance.get("/getFrameWorks?index=1&size=2") .then(r => { // 成功拿到controller中返回的數據  console.log(r) }) 

 

 

運行項目

這樣我們就得到了一個使用HTML作為頁面,C#作為后端的桌面程序

Github地址

全部源碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM