CSharp-Learning/notes/11_WebView2_Basics.md

122 lines
2.9 KiB
Markdown
Raw Normal View History

# WebView2 入门
## 什么是 WebView2
在 Windows 桌面应用里嵌入 Chrome 内核浏览器。
```
┌─────────────────────────┐
│ WPF / WinForms │
│ ┌───────────────────┐ │
│ │ WebView2 │ │
│ │ (Chrome 内核) │ │
│ │ │ │
│ │ ┌─────────────┐ │ │
│ │ │ HTML/CSS/JS │ │ │
│ │ │ 你的界面 │ │ │
│ │ └─────────────┘ │ │
│ └───────────────────┘ │
│ │
│ C# 代码 │
└─────────────────────────┘
```
## 安装 WebView2 Runtime
下载地址https://developer.microsoft.com/en-us/microsoft-edge/webview2/
## NuGet 包
```bash
dotnet add package Microsoft.Web.WebView2
```
## XAML 使用
```xml
<Window xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf">
<Grid>
<wv2:WebView2 x:Name="WebView"
Source="https://example.com"/>
</Grid>
</Window>
```
## 初始化
```csharp
private async void InitializeWebView()
{
await WebView.EnsureCoreWebView2Async();
Console.WriteLine("WebView2 初始化成功");
}
```
## C# 调用 JS
```csharp
// 执行 JS
await WebView.ExecuteScriptAsync("alert('Hello from C#')");
// 获取返回值
string result = await WebView.ExecuteScriptAsync("document.title");
```
## JS 调用 C#
```csharp
// C# 注册方法
WebView.CoreWebView2.WebMessageReceived += (s, e) =>
{
string message = e.TryGetWebMessageAsString();
Console.WriteLine($"收到JS消息: {message}");
};
```
```javascript
// JS 发送消息
window.chrome.webview.postMessage("Hello from JS");
```
## 常用操作
```csharp
WebView.Reload(); // 刷新
WebView.GoBack(); // 后退
WebView.GoForward(); // 前进
WebView.Navigate("https://..."); // 导航到 URL
WebView.CoreWebView2.Settings // 配置
```
## 本地 HTML
```csharp
// 加载本地 HTML 文件
string htmlPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "index.html");
WebView.CoreWebView2.Navigate(new Uri(htmlPath).AbsoluteUri);
// 或者直接加载 HTML 字符串
string html = "<h1>Hello</h1>";
WebView.NavigateToString(html);
```
## 项目里怎么用
```
无言势字幕/
├── MainWindow.xaml ← WPF 窗口,放 WebView2
├── index.html ← 你的界面HTML/CSS/JS
├── WebViewManager.cs ← C# 和 JS 通信
└── AsrService.cs ← 语音识别服务
```
C# 负责:
- 语音识别Sherpa-ONNX
- OSC 发送
- 窗口管理
HTML/JS 负责:
- 界面显示
- 动画效果
- 用户交互