在表单中开始使用 WebView2 Windows表单Get started with WebView2 in Windows Forms

本文将开始创建你的第一个 WebView2 应用,并了解 WebView2 的主要功能In this article, get started creating your first WebView2 app and learn about the main features of WebView2. 有关各个 API 的信息,请导航到 API 参考For more information on individual APIs, navigate to API reference.

必备条件Prerequisites

请确保先安装以下先决条件列表,然后再继续。Ensure you install the following list of pre-requisites before proceeding.

  • WebView2运行时Microsoft Edge (Chromium) 安装在受支持的操作系统 \ (上的任意非稳定通道Windows 10、Windows 8.1和 Windows 7) 。WebView2 Runtime or any Microsoft Edge (Chromium) non-stable channel installed on supported OS (currently Windows 10, Windows 8.1, and Windows 7).

    备注

    WebView 团队建议使用 Canary 通道,最低要求版本为 82.0.488.0。The WebView team recommends using the Canary channel and the minimum required version is 82.0.488.0.

  • Visual Studio 2017 或更高版本。Visual Studio 2017 or later.

备注

WebView2 当前不支持 .NET 5 和 .NET Core 设计器。WebView2 currently does not support the .NET 5 and .NET Core designers.

步骤 1 - 创建单窗口应用Step 1 - Create a single-window app

从包含单个主窗口的基本桌面项目开始。Start with a basic desktop project that contains a single main window.

  1. In Visual Studio, choose Windows Forms .NET Framework App > Next.In Visual Studio, choose Windows Forms .NET Framework App > Next.

    新建项目

  2. 输入 name 和location Project****的值Enter values for Project name and Location. 选择 .NET Framework 4.6.2或更高版本。Choose .NET Framework 4.6.2 or later.

    启动项目

  3. 若要创建项目,请选择"创建 "。To create your project, choose Create.

步骤 2 - 安装 WebView2 SDKStep 2 - Install WebView2 SDK

使用 NuGet 将 WebView2 SDK 添加到项目中。Use NuGet to add the WebView2 SDK to the project.

  1. 将鼠标悬停在项目上,打开上下文菜单 \ (右键单击) ,然后选择"管理NuGet包..."。Hover on the project, open the contextual menu (right-click), and choose Manage NuGet Packages....

    管理 NuGet 包

    管理 NuGet 包Manage NuGet Packages

  2. 在搜索栏中,键入"> Microsoft.Web.WebView2 选择"Microsoft.Web.WebView2"。In the search bar, type Microsoft.Web.WebView2 > choose Microsoft.Web.WebView2.

    NuGet

    开始使用 WebView2 API 开发应用。Start developing apps using the WebView2 API. 若要生成并运行项目,请选择 F5To build and run the project, select F5. 正在运行的项目显示一个空窗口。The running project displays an empty window.

    空应用

步骤 3 - 创建单个 WebViewStep 3 - Create a single WebView

将 WebView 添加到你的应用。Add a WebView to your app.

  1. 打开 "Windows设计器"。Open the Windows Forms Designer.

  2. 在工具箱中搜索 WebView2。 ****Search for WebView2 in the Toolbox.

    备注

    如果使用的是 Visual Studio 2017,则默认情况下 WebView2可能不会显示在工具箱If you are using Visual Studio 2017, by default WebView2 may not display in the Toolbox. 若要启用此行为,请选择"工具 > "" 选项 > ****>"自动填充工具箱"设置设置为 TrueTo enable the behavior, choose Tools > Options > General > set the Automatically Populate Toolbox setting to True.

    WebView2 控件拖放到 Windows Forms App。Drag and drop the WebView2 control into the Windows Forms App.

    显示 WebView2 的工具箱

    显示 WebView2 的工具箱Toolbox displaying WebView2

  3. (Name) 属性设置为 webViewSet the (Name) property to webView.

    WebView2 控件的属性

    WebView2 控件的属性Properties of the WebView2 control

  4. 属性 Source 设置 WebView2 控件中显示的初始 URI。The Source property sets the initial URI displayed in the WebView2 control. Source 属性设置为 https://www.microsoft.comSet the Source property to https://www.microsoft.com.

    WebView2 控件的 Source 属性

    WebView2 控件的 Source 属性The Source property of the WebView2 control

若要生成并运行项目,请选择 F5To build and run your project, select F5. 确保 WebView2 控件显示 [https://www.microsoft.com][|::ref1::|Main] 。Ensure your WebView2 control displays [https://www.microsoft.com][|::ref1::|Main].

hello webview

备注

如果正在处理高 DPI 监视器,可能需要将 Windows Forms 应用配置为高 DPI 支持If you are working on a high DPI monitor, you may have to configure your Windows Forms app for high DPI support.

步骤 4 - 处理窗口大小事件Step 4 - Handle Window Resize Events

从工具箱向窗体中添加Windows控件,然后适当地处理窗口大小事件。Add a few more controls to your Windows Forms from the toolbox, and then handle window resize events appropriately.

  1. "Windows设计器"中,打开"工具箱 "。In the Windows Forms Designer, open the Toolbox.

  2. TextBox 拖放到 Windows Forms 应用程序中。Drag and Drop a TextBox into the Windows Forms App. "属性"选项卡中的 TextBox addressBar 命名Name the TextBox addressBar in the Properties Tab.

  3. 按钮拖放到Windows Forms 应用程序中。Drag and Drop a Button into the Windows Forms App. 将"按钮"中的文本 Go! 更改为 ,并**** 命名"属性"选项卡 goButton 中的"按钮"。Change the text in the Button to Go! and name the Button goButton in the Properties Tab.

    应用应如设计器中的下图所示。The app should look like the following image in the designer.

    WinForms 设计器

  4. Form1.cs 文件中,定义 Form_Resize 以在调整应用窗口大小时保持控件就位。In the Form1.cs file, define Form_Resize to keep the controls in place when the App Window is resized.

public Form1()
{
    InitializeComponent();
    this.Resize += new System.EventHandler(this.Form_Resize);
}

private void Form_Resize(object sender, EventArgs e)
{
    webView.Size = this.ClientSize - new System.Drawing.Size(webView.Location);
    goButton.Left = this.ClientSize.Width - goButton.Width;
    addressBar.Width = goButton.Left - addressBar.Left;
}

若要生成并运行项目,请选择 F5To build and run your project, select F5. 确保应用显示类似于以下屏幕截图。Ensure the app displays similar to the following screenshot.

应用

步骤 5 - 导航Step 5 - Navigation

添加允许用户通过向应用添加地址栏来更改 WebView2 控件显示的 URL 的能力。Add the ability to allow users to change the URL that the WebView2 control displays by adding an address bar to the app.

  1. 选择 F5 以生成并运行项目。Select F5 to build and run your project. 确认应用显示类似于以下屏幕截图。Confirm that the app displays similar to the following screenshot.

    WinForms 应用

  2. Form1.cs 文件中,若要添加 CoreWebView2 命名空间,请将以下代码段插入顶部。In the Form1.csfile, to add the CoreWebView2 namespace, insert the following code snippet at the top.

  3. Form1.cs 添加 CoreWebView2 命名空间时,在 的顶部插入以下代码段 Form1.csIn Form1.cs add the CoreWebView2 namespace by inserting the following code snippet at the top of Form1.cs.

    using Microsoft.Web.WebView2.Core;
    
  4. "Windows设计器"中,双击按钮 Go!goButton_Click 在文件中创建 Form1.cs 方法。In the Windows Forms Designer, double-click on the Go! button to create the goButton_Click method in the Form1.cs file. 复制以下代码段并将其粘贴到 函数中。Copy and paste the following snippet inside the function. 现在, goButton_Click 函数将 WebView 导航到地址栏中输入的 URL。Now, the goButton_Click function navigates the WebView to the URL entered in the address bar.

    private void goButton_Click(object sender, EventArgs e)
    {
        if (webView != null && webView.CoreWebView2 != null)
        {
            webView.CoreWebView2.Navigate(addressBar.Text);
        }
    }
    

若要生成并运行项目,请选择 F5To build and run your project, select F5. 在地址栏中输入新 URL,然后选择"转到 "。Enter a new URL in the address bar, and select Go. 例如,输入 https://www.bing.comFor example, enter https://www.bing.com. 确保 WebView2 控件导航到 URL。Ensure the WebView2 control navigates to the URL.

备注

确保在地址栏中输入完整 URL。Ensure a complete URL is entered in the address bar. 如果 ArgumentException URL 不以 或 为起始,则 http:// 会引发 。An ArgumentException is thrown if the URL does not start with http:// or https://

bing.com

步骤 6 - 导航事件Step 6 - Navigation events

在网页导航期间,WebView2 控件将引发事件。During webpage navigation, the WebView2 control raises events. 承载 WebView2 控件的应用侦听以下事件。The app that hosts WebView2 controls listens for the following events.

  • NavigationStarting
  • SourceChanged
  • ContentLoading
  • HistoryChanged
  • NavigationCompleted

有关详细信息,请导航到"导航事件"。For more information, navigate to Navigation Events.

导航事件

导航事件Navigation events

发生错误时,将引发以下事件,并可能依赖于导航到错误网页。When an error occurs, the following events are raised and may depend on navigation to an error webpage.

  • SourceChanged
  • ContentLoading
  • HistoryChanged

备注

如果发生 HTTP 重定向,则一行 NavigationStarting 中有多个事件。If an HTTP redirect occurs, there are multiple NavigationStarting events in a row.

若要演示如何使用事件,请首先注册一个处理程序,以取消不使用 NavigationStarting HTTPS 的任何请求。To demonstrate how to use the events, start by registering a handler for NavigationStarting that cancels any requests not using HTTPS.

Form1.cs 文件中,更新构造函数以匹配以下代码段并添加 EnsureHttps 函数。In the Form1.cs file, update the constructor to match the following code snippet and add the EnsureHttps function.

public Form1()
{
    InitializeComponent();
    this.Resize += new System.EventHandler(this.Form_Resize);

    webView.NavigationStarting += EnsureHttps;
}

void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
    String uri = args.Uri;
    if (!uri.StartsWith("https://"))
    {
        args.Cancel = true;
    }
}

在构造函数中 EnsureHttps ,注册为 WebView2 控件上事件 NavigationStarting 的事件处理程序。In the constructor, EnsureHttps is registered as the event handler on the NavigationStarting event on the WebView2 control.

若要生成并运行项目,请选择 F5To build and run your project, select F5. 确保导航到 HTTP 网站时,WebView 保持不变。Ensure when navigating to an HTTP site, the WebView remains unchanged. 但是,WebView 将导航到 HTTPS 网站。However, the WebView will navigate to HTTPS sites.

步骤 7 - 脚本Step 7 - Scripting

你可以在运行时使用主机应用将 JavaScript 代码注入 WebView2 控件。You may use host apps to inject JavaScript code into WebView2 controls at runtime. 你可以任务 WebView 运行任意 JavaScript 或添加初始化脚本。You may task WebView to run arbitrary JavaScript or add initialization scripts. 在删除 JavaScript 之前,注入的 JavaScript 适用于所有新的顶级文档和任何子框架。The injected JavaScript applies to all new top-level documents and any child frames until the JavaScript is removed. 注入的 JavaScript 以特定计时运行。The injected JavaScript is run with specific timing.

  • 创建全局对象后运行它。Run it after the creation of the global object.
  • 在运行 HTML 文档中包含的任何其他脚本之前运行它。Run it before any other script included in the HTML document is run.

例如,添加在用户导航到非 HTTPS 网站时发送警报的脚本。As an example, add scripts that send an alert when a user navigates to non-HTTPS sites. 修改 EnsureHttps 函数以将脚本注入到使用 ExecuteScriptAsync 方法的 Web 内容中。Modify the EnsureHttps function to inject a script into the web content that uses ExecuteScriptAsync method.

void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
    String uri = args.Uri;
    if (!uri.StartsWith("https://"))
    {
        webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
        args.Cancel = true;
    }
}

若要生成并运行项目,请选择 F5To build and run your project, select F5. 当你导航到不使用 HTTPS 的网站时,请确保应用显示一个警报。Ensure the app displays an alert when you navigate to a website that doesn't use HTTPS.

https

步骤 8 - 主机和 Web 内容之间的通信Step 8 - Communication between host and web content

主机和 Web 内容可能 postMessage 用于相互通信,如下所示:The host and web content may use postMessage to communicate with each other as follows:

  • WebView2 控件中的 Web 内容可能 window.chrome.webview.postMessage 用于向主机发布消息。Web content in a WebView2 control may use window.chrome.webview.postMessage to post a message to the host. 主机使用主机上注册的任何消息 WebMessageReceived 处理邮件。The host handles the message using any registered WebMessageReceived on the host.
  • 使用 或 将消息张贴到 WebView2 控件中的 CoreWebView2.PostWebMessageAsString Web 内容 CoreWebView2.PostWebMessageAsJSONHosts post messages to web content in a WebView2 control using CoreWebView2.PostWebMessageAsString or CoreWebView2.PostWebMessageAsJSON. 添加到 的处理程序会捕获这些消息 window.chrome.webview.addEventListenerThese messages are caught by handlers added to window.chrome.webview.addEventListener.

通信机制使用本机功能将来自 Web 内容的消息传递给主机。The communication mechanism passes messages from web content to the host using native capabilities.

在项目中,当 WebView2 控件导航到 URL 时,它会在地址栏中显示 URL,并通知用户 WebView2 控件中显示的 URL。In your project, when the WebView2 control navigates to a URL, it displays the URL in the address bar and alerts the user of the URL displayed in the WebView2 control.

  1. Form1.cs 文件中,更新构造函数并创建 InitializeAsync 一个函数以匹配以下代码段。In the Form1.cs file, update your constructor and create an InitializeAsync function to match the following code snippet. 函数 InitializeAsync awaits EnsureCoreWebView2Async, 因为 的初始化 CoreWebView2 是异步的。The InitializeAsync function awaits EnsureCoreWebView2Async because the initialization of CoreWebView2 is asynchronous.

    public Form1()
    {
        InitializeComponent();
        this.Resize += new System.EventHandler(this.Form_Resize);
        webView.NavigationStarting += EnsureHttps;
        InitializeAsync();
    }
    
    async void InitializeAsync()
    {
        await webView.EnsureCoreWebView2Async(null);
    }
    
  2. 初始化 CoreWebView2 后,注册事件处理程序以响应 WebMessageReceivedAfter CoreWebView2 is initialized, register an event handler to respond to WebMessageReceived. Form1.cs 文件中, InitializeAsync 使用下面的代码 UpdateAddressBar 段更新和添加。In the Form1.cs file, update InitializeAsync and add UpdateAddressBar using the following code snippet.

    async void InitializeAsync()
    {
        await webView.EnsureCoreWebView2Async(null);
        webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;
    }
    
    void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
    {
        String uri = args.TryGetWebMessageAsString();
        addressBar.Text = uri;
        webView.CoreWebView2.PostWebMessageAsString(uri);
    }
    
  3. 为了使 WebView 能够发送和响应 Web 消息,在初始化后,主机将 Web 内容中的脚本注入 CoreWebView2 到:In order for the WebView to send and respond to the web message, after CoreWebView2 is initialized, the host injects a script in the web content to:

    1. 使用 将 URL 发送到主机 postMessageSend the URL to the host using postMessage.
    2. 注册事件处理程序以打印从主机发送的消息。Register an event handler to print a message sent from the host.

Form1.cs 文件中,进行更新 InitializeAsync 以匹配以下代码段。In the Form1.cs file, update InitializeAsync to match the following code snippet.

async void InitializeAsync()
{
    await webView.EnsureCoreWebView2Async(null);
    webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;

    await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
    await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));");
}

若要生成并运行应用,请选择 F5To build and run the app, select F5. 现在,地址栏在 WebView2 控件中显示 URI。Now, the address bar displays the URI in the WebView2 control. 此外,当你成功导航到新 URL 时,WebView 会向用户通知 WebView 中显示的 URL。Also, when you successfully navigate to a new URL, the WebView alerts the user of the URL displayed in the WebView.

最终应用

恭喜!你生成了第一个 WebView2 应用。Congratulations, you built your first WebView2 app.

后续步骤Next steps

若要继续了解有关 WebView2 的更多内容,请导航到以下资源。To continue learning more about WebView2, navigate to the following resources.

与 WebView 团队Microsoft Edge联系Getting in touch with the Microsoft Edge WebView team

分享反馈以帮助构建更丰富的 WebView2 体验。Share your feedback to help build richer WebView2 experiences. 若要提交功能请求或 Bug,或搜索已知问题,请导航到 Microsoft Edge WebView 反馈 存储库。To submit feature requests or bugs, or search for known issues, navigate to the Microsoft Edge WebView feedback repo.