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

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

在这里插入图片描述
切记必须是 始终复制
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值