[C#] 簡單使用 Microsoft Edge WebView2 在 WinForms 中的應用
2024-06-03
好久沒寫 WinForms 了,最近因為有一些比較麻煩的需求,所以必須使用 WinForms 來解決問題會比較簡單。
這次的需求是要操控網頁來取得一些資料,經過評估,決定使用 WinForms。然而,想到 WebView 用的是舊版的 IE 核心,本來打算使用第三方的 Chromium 套件,但查了之後發現竟然有 Microsoft 官方推出的 Edge WebView2。
結論是,使用 WebView2 需要注意一些細節,但整體來說與以前的傳統 WebView 相比,有著天壤之別。
打開 NuGet 搜尋 WebView2 並安裝。
https://www.nuget.org/packages/microsoft.web.webview2
安裝後編譯一下,左邊就會出現 WebView2 Windows Forms Control。
所以,我們必須先呼叫 webView21.EnsureCoreWebView2Async(),然後等待初始化完成後才能進行 Navigate。
以下是原始碼示例:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Windows.Forms; | |
namespace TestWebView2 | |
{ | |
public partial class Form1 : Form | |
{ | |
public Form1() | |
{ | |
InitializeComponent(); | |
webView21.EnsureCoreWebView2Async(); | |
webView21.CoreWebView2InitializationCompleted += WebView21_CoreWebView2InitializationCompleted; | |
} | |
private void WebView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e) | |
{ | |
MessageBox.Show("Init Already"); | |
} | |
private void button1_Click(object sender, EventArgs e) | |
{ | |
webView21.CoreWebView2.Navigate("https://developer.microsoft.com/zh-tw/microsoft-edge/webview2/?Wt.mc_id=DT-MVP-4030677"); | |
} | |
private void Form1_Load(object sender, EventArgs e) | |
{ | |
} | |
} | |
} | |
而且還可以叫出開發者的 console 舒服
reference:
https://learn.microsoft.com/en-us/microsoft-edge/webview2/
https://learn.microsoft.com/zh-tw/microsoft-edge/webview2/get-started/winforms