WPF C# 用WebView加载H5页面(uniapp项目,vue项目)

xml 复制代码
<Window
    x:Class="CSharpAllDemo.Web2C.Web2CWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:CSharpAllDemo.Web2C"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
    Title="Web2CWindow"
    Width="800"
    Height="800"
    mc:Ignorable="d">
    <StackPanel Loaded="StackPanel_Loaded">
        <Button Height="40" Content="C#调用JS" Click="Button_Click" />
        <wv2:WebView2
            Name="WebView2"
            Width="800"
            Height="800" />
    </StackPanel>
</Window>
csharp 复制代码
using System.IO;
using System.Windows;

namespace CSharpAllDemo.Web2C
{
    /// <summary>
    /// Web2CWindow.xaml 的交互逻辑
    /// </summary>
    public partial class Web2CWindow : Window
    {
        public Web2CWindow()
        {
            InitializeComponent();
            string htmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Web2C/web/index.html");
            WebView2.Source = new Uri(htmlPath);
        }

        private async void StackPanel_Loaded(object sender, RoutedEventArgs e)
        {
            await WebView2.EnsureCoreWebView2Async();
            WebView2.CoreWebView2.WebMessageReceived += (sender, args) =>
            {
                var message = args.WebMessageAsJson;
                MessageBox.Show(message);
                // 处理来自 JavaScript 的消息
            };
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var message = new { Text = "Hello from C#" };
            WebView2.CoreWebView2.PostWebMessageAsString("123");
        }
    }
}

切记必须是 始终复制

相关推荐
曹牧3 小时前
C#:未被引用的函数
c#
上位机妹子8 小时前
EF Core 两种继承映射:每层次一张表(TPH)与每类型一张表(TPT)
数据库·c#·.netcore·ef core
小羊没烦恼!10 小时前
jQuery1.5的改进细节
java·服务器·开发语言·前端·c#
下页、再停留11 小时前
【C#桌面客户端系列学习-8】批量导出数据为csv格式
开发语言·c#·visual studio
波力海苔夹心脆67512 小时前
C# 视觉检测实战:PLC 按钮触发 VisionPro 检测,OK 亮灯 / NG 灭灯(西门子 PLC,含界面显示与图片存档)
开发语言·经验分享·c#·自动化·视觉检测·.net
2501_9159090613 小时前
iOS应用从开发到上架App Store的完整发布流程与步骤指南
android·ios·小程序·https·uni-app·webview
kim13 小时前
一个人 + AI,用 WinForms 搓了个 376KB 的 Windows 便签:便签 / 截图 / 标注 / OCR / 待办全塞进去了
c#
hez201014 小时前
一行代码在 .NET 项目里启用 Satori GC
c#·.net·.net core·gc·clr
宇卿.14 小时前
C#语句:
开发语言·c#
咕白m62514 小时前
使用 C# 将 TIFF 转换为 PDF
前端·c#