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");
        }
    }
}

切记必须是 始终复制

相关推荐
白菜上路4 分钟前
C# Serilog.AspNetCore基本使用
c#·serilog
小白不白11140 分钟前
C# WinForm 与 VP 二次开发
开发语言·c#
SunnyDays10112 小时前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
伶俜662 小时前
# [特殊字符] 零基础学 ArkUI 数据持久化(专题三):5 种存储方案深度对比
学习·华为·wpf·harmonyos
itgather2 小时前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel
IT策士2 小时前
Redis 从入门到精通:数据结构String 与键管理
数据结构·redis·wpf
云中小生3 小时前
Scrutor:.NET 依赖注入自动化的优雅实现
c#·.net
郝亚军3 小时前
Visual Studio 2022项目中的.sln是什么?
c++·c#·visual studio
jghhh013 小时前
C# 图片水印工具(支持9个位置)
数据库·microsoft·c#
AC赳赳老秦3 小时前
技术文章素材收集自动化:用 OpenClaw 自动爬取行业资讯、技术热点、优质文章
运维·开发语言·python·自动化·wpf·deepseek·openclaw