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

切记必须是 始终复制

相关推荐
厦门德仔1 小时前
【WPF】WPF(样式)
android·java·wpf
耶啵奶膘12 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
葬歌倾城15 小时前
JSON的缩进格式方式和紧凑格式方式
c#·json
Eiceblue16 小时前
使用 C# 发送电子邮件(支持普通文本、HTML 和附件)
开发语言·c#·html·visual studio
小小小小王王王16 小时前
hello判断
开发语言·c#
金增辉18 小时前
基于C#的OPCServer应用开发,引用WtOPCSvr.dll
c#
future141220 小时前
C#学习日记
开发语言·学习·c#
傻啦嘿哟21 小时前
Python 办公实战:用 python-docx 自动生成 Word 文档
开发语言·c#
✎ ﹏梦醒͜ღ҉繁华落℘1 天前
WPF学习(四)
学习·wpf
zzyzxb1 天前
WPF中依赖属性和附加属性
wpf