我正在嘗試在我的 WPF 應用程式中使用嵌入式 WebView2 控制元件,并打開一個 Ookii VistaSaveFileDialog 以回應來自 webview 的通信。
但是,一旦我運行了對話框的ShowDialog方法(在等待用戶回應時阻塞)并且對話框打開,應用程式突然關閉,沒有例外或警告。這會間歇性地發生。
它似乎只發生在我在除錯模式下運行代碼,使用 VS 除錯時。發布模式似乎沒有這個問題。
洗掉bin和obj檔案夾并重建解決方案沒有幫助。
我該如何除錯/解決這個問題?
目標/版本資訊:TFM:net6.0-windows
WebView2:1.0.1210.39
Ookii.Dialogs.Wpf:5.0.1
XAML:
<Window x:Class="_testWebviewDialogs.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wv="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf">
<wv:WebView2 x:Name="webview" Source="about:blank"/>
</Window>
代碼隱藏:
using Ookii.Dialogs.Wpf;
using System.IO;
using System.Windows;
namespace _testWebviewDialogs;
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
initializeAsync();
}
private async void initializeAsync() {
await webview.EnsureCoreWebView2Async();
var html = await File.ReadAllTextAsync("container.html");
webview.NavigateToString(html);
webview.CoreWebView2.WebMessageReceived = (s, e) => {
var dlg = new VistaSaveFileDialog();
dlg.ShowDialog(); // Sometimes the app shuts down while in this (blocking) call
MessageBox.Show(dlg.FileName);
webview.CoreWebView2.PostWebMessageAsString(dlg.FileName);
};
}
}
container.html,將其復制到輸出檔案夾:
<!DOCTYPE html>
<html>
<body>
<button id="button1">Click me</button>
<script>
document.getElementById('button1')
.addEventListener('click', ev => {
chrome.webview.postMessage('Hello from webview');
});
</script>
</body>
</html>
uj5u.com熱心網友回復:
根據我在提交的 GitHub 問題上收到的建議,以下似乎可行:
webview.CoreWebView2.WebMessageReceived = (s, e) =>
SynchronizationContext.Current!.Post((_) => {
var dlg = new VistaSaveFileDialog();
dlg.ShowDialog();
MessageBox.Show(dlg.FileName);
webview.CoreWebView2.PostWebMessageAsString(dlg.FileName);
}, null);
來源:WebView2 應用程式的執行緒模型:可重入
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/475812.html
上一篇:WPF系結串列框選定項到文本框中
