はじめに
Microsoft Internet Explorer もなくなり、Microsoft Edge も Chromium になって世の中が Chromium 一色となりました。Wpf を使ってWeb Browser を作るときは System.Windows.Controls.WebBrowser でしたが、これは内部がIE7というとんでもない骨董品でした。Wpf で Chromium は扱えなくもないですが、微妙に扱いにくいのでどうしたものかと思っていたら Microsoft が Microsoft.Web.WebView2 を出してくれたのでこれをちょっと触ってみることにします。
XAMLに埋め込む
XAMLに埋め込むのはこんな感じです。
- <UserControl x:Class="UserControls.WebBrowser"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
- mc:Ignorable="d"
- d:DesignHeight="450" d:DesignWidth="800">
- <Grid>
- <wv2:WebView2
- x:Name="WebViewer" />
- </Grid>
- </UserControl>
Microsoft.Web.WebView2 は Nuget から拾ってきます。
URLで画面遷移する
アドレスバーの入力など任意のWebページに遷移するのは Source Property を指定します。
- using Microsoft.Web.WebView2.Wpf;
- using System;
- using System.IO;
- using System.Windows;
- using System.Windows.Controls;
- namespace UserControls.WebBrowser;
- public partial class WebBrowser : UserControl
- {
- public WebBrowser()
- {
- InitializeComponent();
- WebViewer..Source = new Uri(@"https://www.lutheta.jp/");
- }
- }
Responseを拾う
Response を拾うには WebResourceResponseReceived を拾えばいいです。ただ、これは Microsoft.Web.WebView2.Wpf.WebView2 の CoreWebView2 Property の Microsoft.Web.WebView2.Core.CoreWebView2 にあるので注意が必要です。
- using Microsoft.Web.WebView2.Wpf;
- using System;
- using System.IO;
- using System.Windows;
- using System.Windows.Controls;
- namespace UserControls.WebBrowser;
- public partial class WebBrowser : UserControl
- {
- public WebBrowser()
- {
- InitializeComponent();
- WebViewer.CoreWebView2InitializationCompleted += (sender, e) =>
- {
- if (sender != null)
- ((WebView2)sender).CoreWebView2.WebResourceResponseReceived += async (sender, e) =>
- {
- }
- };
- }
- }
CoreWebView2 は Component の Initialize 時には Null なので CoreWebView2InitializationCompleted Event で WebResourceResponseReceived Event をセットするようにします。
これを利用して
とりあえず MarineTraffic から航跡を抽出するアプリを作ってみました。
![]() |
MarinTraffic |
なかなか応用幅が広がりそうな感じでです。
0 件のコメント:
コメントを投稿