LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

WebView2 在 Windows Forms 应用程序中的实践

admin
2025年3月8日 14:39 本文热度 156

在现代桌面应用开发中,WebView2控件为开发者提供了一种将Web技术无缝集成到Windows应用程序的强大方式。微软的WebView2基于Chromium内核,为开发者提供了极其灵活的跨平台Web内容展示解决方案,用这个方案完全可以做上位机开发,结合Web的灵活性,与Winform的稳定性。

代码解析

命名空间引入

using System;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;

关键命名空间:

  • System.Windows.Forms
    :提供Windows窗体基础
  • Microsoft.Web.WebView2.Core
    :WebView2核心功能

完整代码

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 Microsoft.Web.WebView2.Core;

namespace AppWebView2
{
    public partial class Form5 : Form
    {
        public Form5()
        
{
            InitializeComponent();
            InitializeWebView();
        }

        private async void InitializeWebView()
        
{

            await webView21.EnsureCoreWebView2Async(null);

            // 设置虚拟主机映射  
            webView21.CoreWebView2.SetVirtualHostNameToFolderMapping(
                "app.local",
                Path.Combine(Application.StartupPath, "dist"),
                CoreWebView2HostResourceAccessKind.Allow
            );

            webView21.Source = new Uri("https://app.local/index.html");
        }
    }
}

关键技术点详解

异步初始化

EnsureCoreWebView2Async(null) 是一个关键的异步方法,确保WebView2运行时正确加载。

虚拟主机映射

SetVirtualHostNameToFolderMapping 方法提供了一种安全的方式将本地文件夹映射到虚拟主机:

  • 第一个参数:虚拟主机名(app.local
  • 第二个参数:本地文件夹路径
  • 第三个参数:资源访问权限

资源加载

使用 https://app.local/index.html 加载本地资源,这是一种安全且灵活的方式。

最佳实践

目录结构建议

YourApp/

├── dist/                   # Vue构建输出目录
│   ├── index.html
│   ├── assets/
│   └── ...

└── YourApp.exe             # 可执行文件

注意:dist目录copy到bin目录下面。

高级功能

JavaScript交互

C# 调用 JavaScript:

await webView21.CoreWebView2.ExecuteScriptAsync("console.log('Hello from C#')");

Vue 调用 C#:

window.chrome.webview.postMessage(JSON.stringify({
  type'action',
  data: { ... }
}));

DevTools支持

webView21.CoreWebView2.OpenDevToolsWindow();

性能与安全

性能优化

  • 使用增量构建
  • 压缩静态资源
  • 懒加载

安全配置

// 设置安全策略
webView21.CoreWebView2.Settings.IsScriptEnabled = true;
webView21.CoreWebView2.Settings.AreDefaultScriptDialogsEnabled = true;

禁用右键

// 禁用默认上下文菜单  
webView21.CoreWebView2.ContextMenuRequested += (sender, args) =>
{
    // 阻止默认上下文菜单  
    args.Handled = true;
};

结论

WebView2为Windows桌面应用程序提供了一种现代、高效的Web内容集成方案。通过正确配置和使用,可以创建功能强大、性能卓越的混合应用程序。

希望这篇详细的技术文章能帮助您深入理解WebView2在Windows Forms中的实践!


该文章在 2025/3/8 14:39:41 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2025 ClickSun All Rights Reserved