当前位置: 首页 > news >正文

WPF+WebView 基础

1、基于.NET8,通过NuGet添加Microsoft.Web.WebView2。

2、MainWindow.xaml代码如下。

<Window x:Class="Demo.MainWindow"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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:Pangu"mc:Ignorable="d"xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"Title="MainWindow" Height="450" Width="800"><Grid><Grid.RowDefinitions><RowDefinition Height="50"/><RowDefinition Height="*"/></Grid.RowDefinitions><StackPanel Grid.Row="0" Orientation="Horizontal"><Button x:Name="btnCallJS" Click="CallJSFunction_Click" Content="C# Call JavaScript" Width="120" Height="30" Margin="10,10,0,10"/></StackPanel><DockPanel Grid.Row="1"><wv2:WebView2 Name="webView"/></DockPanel></Grid></Window>

3、MainWindow.xaml.cs代码如下。

using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Web.WebView2.Core;
using System;
using System.IO;
using System.Windows;
using Path = System.IO.Path;namespace Demo
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();// 页面加载初始化InitializeAsync();// 将C#对象注入到WebView2中InitializeWebViewAsync();}private async void InitializeWebViewAsync(){await webView.EnsureCoreWebView2Async(null);webView.CoreWebView2.AddHostObjectToScript("webBrowserObj", new ScriptCallbackObject());await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("var webBrowserObj = window.chrome.webview.hostObjects.webBrowserObj;");}private async void InitializeAsync(){await webView.EnsureCoreWebView2Async(null);// 获取当前应用程序的目录string appDirectory = AppDomain.CurrentDomain.BaseDirectory+ "Pages\\";// 构造HTML文件的相对路径(假设HTML文件名为index.html)string htmlFilePath = Path.Combine(appDirectory, "index.html");// 将文件路径转换为URIUri htmlFileUri = new Uri(htmlFilePath, UriKind.Absolute);// 设置WebView2的源为HTML文件的URIwebView.Source = htmlFileUri;}private async void CallJSFunction_Click(object sender, RoutedEventArgs e){// 假设你要调用的JavaScript函数名为 ShowAlert,它不接受任何参数string msg = "Hello from C#!";string script = $"ShowAlert('{ msg }');";await webView.CoreWebView2.ExecuteScriptAsync(script);}}
}

4、 ScriptCallbackObject.cs代码如下。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;namespace Demo
{/// <summary>/// JavaScript调用C#函数类/// </summary>[ClassInterface(ClassInterfaceType.AutoDual)][ComVisible(true)]public class ScriptCallbackObject{public void ShowMessage(string message){MessageBox.Show(message);}}
}

5、index.html页面代码如下。

<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>WebView2 Index</title><script>document.addEventListener("DOMContentLoaded", function() {var button = document.getElementById("btnBroadCast");button.addEventListener("click", function() {webBrowserObj.ShowMessage("Hello from JavaScript!");});});function ShowAlert(message) {document.getElementById("title").innerHTML = message;}function showAlert(message) {document.getElementById("title").innerHTML = message;}</script>
</head><body><button id="StartBroadCast">开始广播</button><!-- <button id="btnBroadCCast" hidden="true">开始测试</button> --><button id="btnBroadCast">开始测试</button><h1 id="title"></h1>
</body></html>

6、运行效果如下。

 

http://www.lryc.cn/news/546950.html

相关文章:

  • 国内光子AI智能引擎:OptoChat AI在南京江北新区亮相
  • vscode离线配置远程服务器
  • 【安装】SQL Server 2005 安装及安装包
  • 使用Maven搭建Spring Boot框架
  • 将docker容器打包为.tar包
  • SYSTEM文件夹下的文件
  • GPPT: Graph Pre-training and Prompt Tuning to Generalize Graph Neural Networks
  • 【SegRNN 源码理解】PMF的多步并行预测
  • 构建自己的AI客服【根据用户输入生成EL表达式】
  • (50)[HGAME 2023 week2]before_main
  • 机器学习数学基础:39.样本和隐含和残差协方差矩阵
  • java之http传MultipartFile文件
  • 深入解析SpringMVC中Http响应的实现机制
  • 构建一个支持精度、范围和负数的-Vue-数字输入框
  • 尚硅谷爬虫note14
  • 1438. 绝对差不超过限制的最长连续子数组
  • ZCC5090EA适用于TYPE-C接口,集成30V OVP功能, 最大1.5A充电电流,带NTC及使能功能,双节锂电升压充电芯片替代CS5090EA
  • Dify 开源大语言模型应用开发平台使用(二)
  • 【LangFuse】数据集与测试
  • 【Python】如何解决Jupyter Notebook修改外部模块后必须重启内核的问题?
  • Redis 篇
  • React + TypeScript 实战指南:用类型守护你的组件
  • 从零开始:Linux环境下如何制作静态库与动态库
  • 【智能体Agent】ReAct智能体的实现思路和关键技术
  • Java进阶:Zookeeper相关笔记
  • QT-绘画事件
  • 鸿蒙NEXT开发-端云一体化开发
  • 大模型——股票分析AI工具开发教程
  • nexus 实现https 私有镜像搭建
  • 颈椎X光数据集(cervical spine X-ray dataset)