录了个视频,包含了整个过程。
视频地址: https://streamja.com/ooRpn
步骤和源代码:
1、安装运行库 https://go.microsoft.com/fwlink/p/?LinkId=2124703
2、创建项目
3、安装 Microsoft.Web.WebView2
4、编写XAML代码
[C#] 纯文本查看 复制代码 <Window x:Class="WebApp.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:WebApp"
xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<DockPanel>
<DockPanel DockPanel.Dock="Top">
<Button x:Name="ButtonGo" DockPanel.Dock="Right" Click="ButtonGo_Click" Content="Go"/>
<TextBox Name = "addressBar" Text=""/>
</DockPanel>
<wv2:WebView2 Name = "webView"
Source = "https://im.qq.com"
/>
</DockPanel>
</Window>
5、编写CS代码
[C#] 纯文本查看 复制代码 public MainWindow()
{
InitializeComponent();
webView.NavigationStarting += EnsureHttps;
}
void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
String uri = args.Uri;
if (!uri.StartsWith("https://"))
{
webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
args.Cancel = true;
}
}
private void ButtonGo_Click(object sender, RoutedEventArgs e)
{
if (webView != null && webView.CoreWebView2 != null)
{
webView.CoreWebView2.Navigate(addressBar.Text);
}
}
|