Getting started with WebView2 in Windows Forms
In this article, get started creating your first WebView2 app and learn about the main features of WebView2. For more information on individual APIs, navigate to API reference.
Prerequisites
Ensure you install the following list of pre-requisites before proceeding.
WebView2 Runtime or any Microsoft Edge (Chromium) non-stable channel installed on supported OS (currently Windows 10, Windows 8.1, and Windows 7).
Note
The WebView team recommends using the Canary channel and the minimum required version is 82.0.488.0.
Visual Studio 2017 or later.
Note
WebView2 currently does not support the .NET 5 and .NET Core designers.
Step 1 - Create a single-window app
Start with a basic desktop project that contains a single main window.
In Visual Studio, choose Windows Forms .NET Framework App > Next.
Enter values for Project name and Location. Choose .NET Framework 4.6.2 or later.
To create your project, choose Create.
Step 2 - Install WebView2 SDK
Use NuGet to add the WebView2 SDK to the project.
Hover on the project, open the contextual menu (right-click), and choose Manage NuGet Packages....
Manage NuGet Packages
In the search bar, type
Microsoft.Web.WebView2
> choose Microsoft.Web.WebView2.Start developing apps using the WebView2 API. To build and run the project, select
F5
. The running project displays an empty window.
Step 3 - Create a single WebView
Add a WebView to your app.
Open the Windows Forms Designer.
Search for WebView2 in the Toolbox.
Note
If you are using Visual Studio 2017, by default WebView2 may not display in the Toolbox. To enable the behavior, choose Tools > Options > General > set the Automatically Populate Toolbox setting to
True
.Drag and drop the WebView2 control into the Windows Forms App.
Toolbox displaying WebView2
Set the
(Name)
property towebView
.Properties of the WebView2 control
The
Source
property sets the initial URI displayed in the WebView2 control. Set theSource
property tohttps://www.microsoft.com
.The Source property of the WebView2 control
To build and run your project, select F5
. Ensure your WebView2 control displays https://www.microsoft.com.
Note
If you are working on a high DPI monitor, you may have to configure your Windows Forms app for high DPI support.
Step 4 - Handle Window Resize Events
Add a few more controls to your Windows Forms from the toolbox, and then handle window resize events appropriately.
In the Windows Forms Designer, open the Toolbox
Drag and drop a TextBox into the Windows Forms App. In the Properties Tab, name the TextBox
addressBar
.Drag and drop a Button into the Windows Forms App. Change the text in the Button to
Go!
and name the ButtongoButton
in the Properties Tab.The app should look like the following image in the designer.
In the
Form1.cs
file, defineForm_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;
}
To build and run your project, select F5
. Ensure the app displays similar to the following screenshot.
Step 5 - Navigation
Add the ability to allow users to change the URL that the WebView2 control displays by adding an address bar to the app.
In the
Form1.cs
file, to add theCoreWebView2
namespace, insert the following code snippet at the top.using Microsoft.Web.WebView2.Core;
In the Windows Forms Designer, double-click on the
Go!
button to create thegoButton_Click
method in theForm1.cs
file. Copy and paste the following snippet inside the function. Now, thegoButton_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); } }
To build and run your project, select F5
. Enter a new URL in the address bar, and select Go. For example, enter https://www.bing.com
. Ensure the WebView2 control navigates to the URL.
Note
Ensure a complete URL is entered in the address bar. An ArgumentException
is thrown if the URL does not start with http://
or https://
Step 6 - Navigation events
During webpage navigation, the WebView2 control raises events. 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
Note
If an HTTP redirect occurs, there are multiple NavigationStarting
events in a row.
To demonstrate how to use these events, start by registering a handler for NavigationStarting
that cancels any requests that don't use HTTPS.
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;
}
}
In the constructor, EnsureHttps is registered as the event handler on the NavigationStarting
event on the WebView2 control.
To build and run your project, select F5
. Ensure when navigating to an HTTP site, the WebView remains unchanged. However, the WebView will navigate to HTTPS sites.
Step 7 - Scripting
You may use host apps to inject JavaScript code into WebView2 controls at runtime. You may task WebView to run arbitrary JavaScript or add initialization scripts. The injected JavaScript applies to all new top-level documents and any child frames until the JavaScript is removed. The injected JavaScript is run with specific timing.
- Run it after the creation of the global object.
- Run it before any other script included in the HTML document is run.
As an example, add scripts that send an alert when a user navigates to non-HTTPS sites. 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;
}
}
To build and run your project, select F5
. Ensure the app displays an alert when you navigate to a website that doesn't use HTTPS.
Step 8 - Communication between host and web content
The host and web content may use postMessage
to communicate with each other as follows:
- Web content in a WebView2 control may use
window.chrome.webview.postMessage
to post a message to the host. The host handles the message using any registeredWebMessageReceived
on the host. - Hosts post messages to web content in a WebView2 control using
CoreWebView2.PostWebMessageAsString
orCoreWebView2.PostWebMessageAsJSON
. These messages are caught by handlers added towindow.chrome.webview.addEventListener
.
The communication mechanism passes messages from web content to the host using native capabilities.
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.
In the
Form1.cs
file, update your constructor and create anInitializeAsync
function to match the following code snippet. TheInitializeAsync
function awaits EnsureCoreWebView2Async because the initialization ofCoreWebView2
is asynchronous.public Form1() { InitializeComponent(); this.Resize += new System.EventHandler(this.Form_Resize); webView.NavigationStarting += EnsureHttps; InitializeAsync(); } async void InitializeAsync() { await webView.EnsureCoreWebView2Async(null); }
After
CoreWebView2
is initialized, register an event handler to respond toWebMessageReceived
. In theForm1.cs
file, updateInitializeAsync
and addUpdateAddressBar
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); }
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:- Send the URL to the host using
postMessage
. - Register an event handler to print a message sent from the host.
- Send the URL to the host using
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));");
}
To build and run the app, select F5
. Now, the address bar displays the URI in the WebView2 control. Also, when you successfully navigate to a new URL, the WebView alerts the user of the URL displayed in the WebView.
Congratulations, you built your first WebView2 app.
Next steps
To continue learning more about WebView2, navigate to the following resources.
See also
- For a comprehensive example of WebView2 capabilities, navigate to WebView2Samples.
- For more information about WebView2, navigate to WebView2 Resources.
- For detailed information about the WebView2 API, navigate to API reference.
Getting in touch with the Microsoft Edge WebView team
Share your feedback to help build richer WebView2 experiences. To submit feature requests or bugs, or search for known issues, see the Microsoft Edge WebView feedback repo.