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

切记必须是 始终复制

相关推荐
SAJalon3 小时前
C#集合全面解析
c#
耶啵奶膘3 小时前
uniapp+vue3——通知栏标题纵向滚动切换
uni-app
SAJalon4 小时前
C#数组全面解析
c#
henreash5 小时前
xLua和C#交互
开发语言·c#·交互
The_era_achievs_hero6 小时前
UniappDay03
vue.js·微信小程序·uni-app
慢慢沉14 小时前
C#(基本语法)
c#
★YUI★17 小时前
学习游戏制作记录(克隆技能)7.25
学习·游戏·unity·c#
坚持吧202118 小时前
【无标题】word 中的中文排序
开发语言·c#
_oP_i18 小时前
c# openxml 打开加密 的word读取内容
开发语言·c#·word
醉酒的李白、19 小时前
C#观察者模式示例代码
观察者模式·c#