WinForm使用WebView2开发现代应用
在微信公众号中看到可以使用WinForm来构建Web应用程序,于是尝试自己制作一个简单的应用。
在WinForm中主要是使用WebView2控件来构建的。
第一步:新建WinForm程序,布局界面如下:
第二步:使用NuGet包管理工具下载WebView2控件
如下图:
笔者项目已经安装完了,直接在工具箱中使用即可。
上面是一个TextBox控件,和一个按钮;TetxBox控件填写网址,点击按钮访问相应的网址。
第三步:编写代码。如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
namespace WebViewTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Resize += new System.EventHandler(this.Form1_Resize);
}
private void Form1_Resize(object sender, EventArgs e)
{
webView.Size = this.ClientSize - new System.Drawing.Size(webView.Location);
button1.Left = this.ClientSize.Width - button1.Width;
textBox1.Width = button1.Left - textBox1.Left;
}
private void button1_Click(object sender, EventArgs e)
{
if (webView != null && webView.CoreWebView2 != null)
{
if (string.IsNullOrEmpty(textBox1.Text) == false)
{
webView.CoreWebView2.Navigate(textBox1.Text);
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Form1_Resize(sender,e);
}
}
}
下面是输入百度网址后的运行效果:
参考文献:
好了,在WinForm中简单使用WebView2控件的介绍就到这里了。关于WebView2控件的更详细是使用方式,大家可以参考官方文档。