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

切记必须是 始终复制

相关推荐
almighty277 小时前
C# WinForm分页控件实现与使用详解
c#·winform·分页控件·c#分页·winform分页
almighty278 小时前
C#实现导入CSV数据到List<T>的完整教程
c#·csv·格式转换·c#导入数据·csv数据导入
吴传逞8 小时前
记一次uniapp微信小程序开发scss变量失效的问题
微信小程序·uni-app·scss
程序猿多布9 小时前
Lua和C#比较
c#·lua
2501_9159214316 小时前
小团队如何高效完成 uni-app iOS 上架,从分工到工具组合的实战经验
android·ios·小程序·uni-app·cocoa·iphone·webview
csdn_aspnet17 小时前
使用 MongoDB.Driver 在 C# .NETCore 中实现 Mongo DB 过滤器
mongodb·c#·.netcore
2501_9160088918 小时前
uni-app iOS 文件管理与 itools 配合实战,多工具协作的完整流程
android·ios·小程序·https·uni-app·iphone·webview
!win !19 小时前
uni-app项目Tabbar实现切换icon动效
小程序·uni-app
xw519 小时前
uni-app项目Tabbar实现切换icon动效
前端·uni-app