It’s easy to build chromium and use Webview2, which is very useful to use. It’s very easy and fast to use Webview2, which is very useful to use.

The final result

Concrete implementation steps

1. Winform builds a shell and adds webView2 components

Open visual studio 2019 and create a Windows forms application in c#


Tools -NuGet Package Management – Search install Webview2, add project, install


Return to Form Designer -WebView2- Drag the WinForms WebView2 control to the appropriate position on the form, name=webView21

Set the form property -source, which opens the browser’s default url, such as juejin


2. Add buttons such as Back, Forward, and Go in the address bar

Add three button controls: back button, forward button, Go button, and address bar

Double click the back button to bind the GoBack() event

        private void goback_Click(object sender, EventArgs e)
        {
            webView21.GoBack();
        }
Copy the code

Double click the forward button to bind the GoForward() event to implement the forward function

       private void goforwd_Click(object sender, EventArgs e)
        {
            webView21.GoForward();
        }
Copy the code

Select the address bar in the form designer, double-click keyDown in the event properties panel to open the entered URL when pressing enter

private void address_KeyDown_1(object sender, KeyEventArgs e)
        {
            String url = address.Text;
            if (e.KeyCode == Keys.Enter && url.Length > 0)
            {
                if (!url.StartsWith("http"))
                {
                    url = "http://" + url;
                }
                webView21.CoreWebView2.Navigate(url);
            }
        }

Copy the code

Double click the Go button to bind and open the URL. If HTTP does not exist, it will be added automatically. This is the same as the keyDown event

private void go_Click(object sender, EventArgs e)
        {
            String url = address.Text;
            if (url.Length > 0)
            {
                if (!url.StartsWith("http"))
                {
                    url = "http://" + url;
                }
                webView21.CoreWebView2.Navigate(url);
            }

        }
Copy the code

After the page is loaded, you need to check whether the page can be moved forward or backward. To check whether the backward and forward buttons can be disabled or enabled, the CanGoBack CanGoForward attribute can be used. If the buttons cannot be executed, the corresponding buttons can be disabled

void EndNav(object sender, CoreWebView2NavigationCompletedEventArgs args){
            this.goback.Enabled = webView21.CanGoBack ? true : false;
            this.goforwd.Enabled = webView21.CanGoForward ? true : false;
}
Copy the code

The method in Form1 construction method binding webView21. NavigationCompleted + = EndNav;

3. Force all pages to be displayed in this window. That is, disable “target=’_blank’ and open a new window

The designer selected webview21, double-click on the CoreWebView2InitializationCompleted properties window, add code, binding NewWindowRequested events

/ / ban new window private void webView21_CoreWebView2InitializationCompleted (object sender, CoreWebView2InitializationCompletedEventArgs e) { webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested; }Copy the code

Disallow code implementation in CoreWebView2_NewWindowRequested method

private void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e) { String url = e.Uri.ToString(); if (! url.Contains("oauth")) { webView21.Source = new Uri(url); e.Handled = true; // Disable pop-ups}}Copy the code

Here we need to make a simple judgment. If the URL contains OAUth characters, it is usually oAUth authorized login window, such as wechat login, etc. At this time, it is allowed to pop up in the new window, otherwise there will be problems in login

4. Automatically adjust the page display according to the window size

In the constructor for Form1, add

this.Resize += new System.EventHandler(this.Form1_Resize);

private void Form1_Resize(object sender, EventArgs e){
            webView21.Size = this.ClientSize - new System.Drawing.Size(webView21.Location);
            go.Left = this.ClientSize.Width - go.Width;
            address.Width = go.Left - address.Left;
}
Copy the code

4. Integration webview2runtime

On the MSDN documentation developer.microsoft.com/zh-cn/micro… There are two integration approaches

One is boot installation. The advantage is that the packaged program is smaller because it does not need to integrate the runtime, but the disadvantage is that it needs to download and install online when it is opened for the first time, which is time-consuming

The second is a direct independent installation program. When you open it for the first time, if you detect that there is no Runtime on the computer, you will install it directly. The advantage is relatively faster, but the disadvantage is also obvious, the installation package is very large.

Determine whether webView2Runtime already exists in the computer environment

public static bool IsInstallWebview2() { string? res = ""; try { res = CoreWebView2Environment.GetAvailableBrowserVersionString(); } catch (System.Exception) { } if (res == "" || res == null) { return false; } return true; } public static void InstallWebview2Async() { if (! IsInstallWebview2()) {form1.gui.text = "Init "; Form1.Gui.Size = new System.Drawing.Size(800, 50); Form1.Gui.MaximizeBox = false; string MicrosoftEdgeWebview2Setup = System.IO.Path.Combine(Application.StartupPath, "MicrosoftEdgeWebView2RuntimeInstallerX64.exe"); Process.Start(MicrosoftEdgeWebview2Setup, " /silent /install").WaitForExit(); If (IsInstallWebview2()) {// Restart application.restart (); Process.GetCurrentProcess()? .Kill(); }}}Copy the code

In the Form1 constructor, start a Task asynchronous Task, check it, and install it. As for the reason why a single task is created, it is time-consuming. If it is executed in the same thread, it will be stuck for a period of time, which makes people uncomfortable.

    Task.Run(() => InstallCheck.InstallWebview2Async());
Copy the code

5. Packaging

Vs menu – generated – packaging, and then from developer.microsoft.com/zh-cn/micro… Download the independent installation package and save it in the same directory as the packaged EXE

Form1. Cs source

using Microsoft.Web.WebView2.Core; using System; using System.Diagnostics; using System.Threading.Tasks; using System.Windows.Forms; namespace webview2 { public partial class Form1 : Form { public static Form Gui; public Form1() { Gui = this; InitializeComponent(); This.resize += new System.eventhandler (this.form1_resize); / / change the window title webView21. NavigationStarting + = EnsureHttps; / / enabled or disabled The back button webView21. NavigationCompleted + = EndNav; / / detection and automatic installation webview2runtime Task. Run (() = > InstallCheck. InstallWebview2Async ()); } void EndNav(object sender, CoreWebView2NavigationCompletedEventArgs args) { this.goback.Enabled = webView21.CanGoBack ? true : false; this.goforwd.Enabled = webView21.CanGoForward ? true : false; } / / navigation began to void EnsureHttps (object sender, CoreWebView2NavigationStartingEventArgs args) {String uri = args. Uri; address.Text = uri; Form1.ActiveForm.Text = webView21.CoreWebView2.DocumentTitle.Length > 1 ? webView21.CoreWebView2.DocumentTitle : this.Text; } private void Form1_Resize(object sender, EventArgs e) { webView21.Size = this.ClientSize - new System.Drawing.Size(webView21.Location); go.Left = this.ClientSize.Width - go.Width; address.Width = go.Left - address.Left; } private void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e) { String url = e.Uri.ToString(); if (! url.Contains("oauth")) { webView21.Source = new Uri(url); e.Handled = true; / / ban pop-up}} / / new window private void webView21_CoreWebView2InitializationCompleted (object sender, CoreWebView2InitializationCompletedEventArgs e) { webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested; } // go button private void go_Click(object sender, EventArgs e) {String URL = address.text; if (url.Length > 0) { if (! url.StartsWith("http")) { url = "http://" + url; } webView21.CoreWebView2.Navigate(url); Private void address_KeyDown_1(Object sender, KeyEventArgs e) {// messagebox.show (e.keycode.tostring (), "bb"); String url = address.Text; if (e.KeyCode == Keys.Enter && url.Length > 0) { if (! url.StartsWith("http")) { url = "http://" + url; } webView21.CoreWebView2.Navigate(url); Private void goback_Click(object sender, EventArgs e) {webView21.goback (); } private void goforwd_Click(object sender, EventArgs e) {webView21.goForward (); Public static class InstallCheck {public static bool IsInstallWebview2() {string? res = ""; try { res = CoreWebView2Environment.GetAvailableBrowserVersionString(); } catch (System.Exception) { } if (res == "" || res == null) { return false; } return true; } public static void InstallWebview2Async() { if (! IsInstallWebview2()) {form1.gui.text = "Init "; Form1.Gui.Size = new System.Drawing.Size(800, 50); Form1.Gui.MaximizeBox = false; string MicrosoftEdgeWebview2Setup = System.IO.Path.Combine(Application.StartupPath, "MicrosoftEdgeWebView2RuntimeInstallerX64.exe"); Process.Start(MicrosoftEdgeWebview2Setup, " /silent /install").WaitForExit(); If (IsInstallWebview2()) {// Restart application.restart (); Process.GetCurrentProcess()? .Kill(); } } } } }Copy the code

The resources

  1. Download webview2 developer.microsoft.com/zh-cn/micro…
  2. Distribute webveiW2Runtime docs.microsoft.com/zh-cn/micro…
  3. Docs.microsoft.com/zh-cn/micro webview2 document…