本文主要是介绍[C#][原创]webview2简单使用,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、本例子需要下载
Microsoft.Web.WebView2
WebView2.Runtime.X64或者WebView2.Runtime.X86
引用库:
webview2运行库这样放置:
代码如下:
using Microsoft.Web.WebView2.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WindowsFormsApplication1
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private async void Form1_Load(object sender, EventArgs e){await webView21.EnsureCoreWebView2Async(await CoreWebView2Environment.CreateAsync(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WebView2")));this.webView21.CoreWebView2.Navigate("https://www.baidu.com");//webView21.Source = new Uri("https://www.baidu.com");webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;}void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e){var deferral = e.GetDeferral();//e.NewWindow = (CoreWebView2)sender;e.NewWindow = this.webView21.CoreWebView2;e.NewWindow.Navigate(e.Uri);deferral.Complete();//e.Handled = true;}private void webView21_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e){}private void webView21_SourceChanged(object sender, CoreWebView2SourceChangedEventArgs e){Console.WriteLine(this.webView21.Source.AbsoluteUri);}private void webView21_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e){}private void webView21_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs e){}}
}
上述代码解决了2个常见问题:
(1)this.webView21.CoreWebView2的值一直是null,这是没有运行库导致
(2)内部跳转,网上说的没有一个完整,正确方式如上图要加个 e.NewWindow.Navigate(e.Uri);不然跳转后空窗口啥也没有。亲测通过,绝对原创。
这篇关于[C#][原创]webview2简单使用的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!