Microsoft.Web.WebView2
是一个用于在 Windows 应用程序中嵌入 Web 内容的控件。它基于 Microsoft Edge (Chromium) 引擎,提供了现代的网页浏览体验。本文将介绍 WebView2 的基本属性和方法,并提供示例代码。
Nuget 安装

基本属性
Source
Source
属性用于获取或设置 WebView2 控件加载的网页地址。
private void btnSource_Click(object sender, EventArgs e)
{
// 设置 WebView2 控件的源地址
webView21.Source = new Uri("https://www.bing.com");
}

CanGoBack
CanGoBack
属性指示 WebView2 控件是否可以返回到上一个页面。
private void btnGoBack_Click(object sender, EventArgs e)
{
// 检查是否可以返回
if (webView21.CanGoBack)
{
webView21.GoBack(); // 返回上一个页面
}
}
CanGoForward
CanGoForward
属性指示 WebView2 控件是否可以前进到下一个页面。
private void btnGoForward_Click(object sender, EventArgs e)
{
// 检查是否可以前进
if (webView21.CanGoForward)
{
webView21.GoForward(); // 前进到下一个页面
}
}

ZoomFactor
ZoomFactor
属性用于获取或设置 WebView2 控件的缩放因子。
private void btnZoomFactor_Click(object sender, EventArgs e)
{
// 设置缩放因子为 1.5
webView21.ZoomFactor = 1.5;
}
基本方法
Navigate
Navigate
方法用于加载指定的 URL。
private void txtAddress_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
webView21.CoreWebView2.Navigate(txtAddress.Text);
}
}

GoBack
GoBack
方法用于返回到上一个页面。
// 返回上一个页面
webView.GoBack();
GoForward
GoForward
方法用于前进到下一个页面。
// 前进到下一个页面
webView.GoForward();
Reload
Reload
方法用于重新加载当前页面。
// 重新加载当前页面
private void btnReload_Click(object sender, EventArgs e)
{
webView21.CoreWebView2.Reload();
}

Stop
Stop
方法用于停止当前页面的加载。
// 停止当前页面的加载
private void btnStop_Click(object sender, EventArgs e)
{
webView21.Stop();
}
总结
Microsoft.Web.WebView2
提供了强大的功能来在 Windows 应用程序中嵌入 Web 内容。通过使用基本属性和方法,开发者可以轻松实现网页的加载、导航和控制。希望本文能帮助你更好地理解和使用 WebView2 控件。
阅读原文:原文链接
该文章在 2025/2/13 8:45:43 编辑过