C# WebView2: A Comprehensive Guide for Developers

Author

Reads 713

A Man Sitting in Front of the Computer while Working
Credit: pexels.com, A Man Sitting in Front of the Computer while Working

C# WebView2 is a powerful tool that allows developers to embed a web browser directly into their Windows desktop applications. It's built on top of the Chromium engine, which means it's fast, secure, and reliable.

One of the key benefits of WebView2 is its ability to run modern web applications, including those that require JavaScript and other web technologies. This makes it an ideal choice for developers who want to create rich, interactive user experiences.

With WebView2, developers can easily integrate web content into their applications, including web pages, web views, and even entire web applications. This allows for a seamless user experience, where the web content feels like it's part of the native application.

WebView2 also provides a range of APIs and features that make it easy to customize and extend the web browser experience, including support for custom JavaScript bridges and event handlers.

For another approach, see: C O a S

Getting Started

To get started with C# WebView2, you'll need to install the necessary tools, including Visual Studio and the WebView2 SDK. See the sequence of samples to install and run for a step-by-step guide.

Credit: youtube.com, Bringing the Best of the Web to Your .NET Windows Apps with WebView2

Installing the WebView2 SDK is a straightforward process, especially when using NuGet, Microsoft's package manager for .NET. This SDK provides the necessary libraries and tools to embed web content into your applications using WebView2.

To integrate WebView2 into a C# project, you'll need to add the WebView2 SDK through NuGet. This can be done by installing the package and then dragging and dropping the WebView2 control onto a Form. The control should then be initialized using the EnsureCoreWebView2Async() method.

Here's a step-by-step guide to get you started:

  1. Install Visual Studio and the WebView2 SDK.
  2. Install and run the main sample.
  3. Install and run the sample for your target platform.
  4. Install and run the finished Getting Started tutorial for your target platform.
  5. Do the Getting Started steps to add WebView2 code to the Visual Studio starter project for your platform.

Install SDK

To install the WebView2 SDK, you'll use the NuGet package manager within Visual Studio.

First, right-click the project name in Solution Explorer and select Manage NuGet Packages. This opens the NuGet Package Manager.

Clear the Include prerelease checkbox and type WebView2 in the search bar. Below the search bar, click Microsoft.Web.WebView2 to select it.

Click the Install (or Update) button, then click OK in the Preview Changes dialog.

Select File > Save All (Ctrl+Shift+S) to save the project, then close the NuGet Package Manager window.

Create a Control

A woman browsing the web on a tablet, sitting in an office environment
Credit: pexels.com, A woman browsing the web on a tablet, sitting in an office environment

To add a WebView2 control to your app, you'll need to install the WebView2 SDK for your WinForms project. This involves adding the Microsoft.Web.WebView2 SDK NuGet package through NuGet, Microsoft's package manager for .NET.

The WebView2 control is available on NuGet, so you can easily install it in your project. Once installed, you can drag and drop it onto a Form in your Visual Studio project.

The control should be initialized by calling the EnsureCoreWebView2Async() method, which guarantees that the CoreWebView2 property is initialized and won't throw a null reference exception.

Here's a step-by-step guide to initializing the WebView2 control:

1. Create a new Form in your project.

2. Drag and drop the WebView2 control from the Toolbox onto the Form.

3. Call the InitializeWebView2() method and await the EnsureCoreWebView2Async() method to initialize the control.

By following these steps, you'll be able to create a WebView2 control in your WinForms project and start embedding web content into your application.

Navigation

Credit: youtube.com, Web view in Winforms C# using Microsoft.webview2

Navigation is a core feature of WebView2 in C#. To enable users to change the URL displayed in the WebView2 control, you need to read the text entered in the text box, which serves as an Address bar. This is achieved by adding the CoreWebView2 namespace, registering an event handler for NavigationStarting, and calling the Navigate method.

You can navigate to a site by calling the Navigate method, but it has to start with "https" or "http". For example, you can load Microsoft's website by calling webView.CoreWebView2.Navigate("https://microsoft.com").

To handle navigation events, you can register event handlers for events such as NavigationStarting, SourceChanged, ContentLoading, HistoryChanged, and NavigationCompleted. These events are raised during webpage navigation and can be used to respond to user interactions or errors.

Here is a list of navigation events that can be handled:

  • NavigationStarting
  • SourceChanged
  • ContentLoading
  • HistoryChanged
  • NavigationCompleted

Host-Web Communication

Host-Web Communication is a crucial aspect of Navigation in WebView2. The host and web content can use postMessage to communicate with each other.

Monitor Displaying Computer Application
Credit: pexels.com, Monitor Displaying Computer Application

The communication mechanism passes messages from web content to the host using native capabilities. This is achieved through the use of window.chrome.webview.postMessage in the web content and CoreWebView2.PostWebMessageAsString or CoreWebView2.PostWebMessageAsJSON in the host.

To establish this communication, the host must first initialize the CoreWebView2 control asynchronously. This is done by calling the EnsureCoreWebView2Async method.

The host then registers an event handler to respond to WebMessageReceived. This event handler will be triggered when the web content posts a message to the host.

In the event handler, the host can retrieve the message as a string using the TryGetWebMessageAsString method. The host can then update the address bar with the received URL.

To send and respond to the web message, the host injects a script into the web content. This script posts the current URL to the host using window.chrome.webview.postMessage.

Here's a summary of the steps involved in host-web communication:

  • Initialize the CoreWebView2 control asynchronously
  • Register an event handler to respond to WebMessageReceived
  • Retrieve the message as a string in the event handler
  • Update the address bar with the received URL
  • Inject a script into the web content to post the current URL to the host

Go to website

To navigate to a website, you'll need to use the Navigate() method. This method requires the URL to start with either "https" or "http".

Credit: youtube.com, Website Navigation No-No's

You can enable users to change the URL by reading the text entered in the text box to serve as an Address bar. To do this, add the CoreWebView2 namespace and paste the code into the file to replace the empty goButton_Click method.

The method body should be as follows: private void goButton_Click(object sender, EventArgs e) { if (webView != null && webView.CoreWebView2 != null) { webView.CoreWebView2.Navigate(addressBar.Text); } }.

If the URL doesn't start with "http" or "https", an ArgumentException is thrown.

Here's a quick rundown of the steps to navigate to a website:

  • Load the website by calling the Navigate() method.
  • The URL must start with either "https" or "http".
  • Use the text entered in the text box as the URL by reading the text entered in the text box.
  • Handle the ArgumentException if the URL doesn't start with "http" or "https".

You can test this by entering a URL that starts with "https" and clicking the Go! button. The WebView2 control will show the webpage content for the URL.

Loading Content

Loading content with WebView2 is a straightforward process. You can load web pages by specifying a URL or loading HTML content directly.

To load a web page, you can use the Navigate method, as shown in Example 2: "Loading Web Pages in WebView2". This method navigates the WebView2 control to a specified web page, displaying it within the application.

Credit: youtube.com, How to receive data from webview2 C#

You can also load custom HTML content, as demonstrated in Example 3: "Load Custom HTML#". This method allows you to pass HTML content to the control, up to 2 MB in size.

When loading custom HTML, you can also inject JavaScript and CSS code into the page. This can be done using the AddScriptToExecuteOnDocumentCreatedAsync method, which runs the script before the HTML has been parsed.

Here are some key points to keep in mind when using AddScriptToExecuteOnDocumentCreatedAsync:

  • The script runs before the HTML has been parsed.
  • You can check the document's readyState to ensure it's complete before accessing elements.
  • Scripts added using this method will run on every page load until you call RemoveScriptToExecuteOnDocumentCreated.

It's worth noting that scripts added using AddScriptToExecuteOnDocumentCreatedAsync will stick around and run again on every page load until you call RemoveScriptToExecuteOnDocumentCreated. To see what I mean, try adding a script that changes the background color of the page.

Displaying Content

You can display web content in your C# application using WebView2, which enables you to embed and display standard web content, including HTML pages, Cascading Style Sheets for styling, and JavaScript for interactivity.

The control functions are similar to a web browser embedded within your application, rendering web content as it would appear in Microsoft Edge.

Credit: youtube.com, Using WebView in WPF: The .NET Show with Carl Franklin Ep 34

To load web pages, you can specify a URL or load HTML content directly. For example, you can navigate the WebView2 control to a specified web page, displaying it within the application.

Customizing the web experience is also possible, allowing you to control how web content is displayed and customize various aspects, such as size, visibility, and user interaction settings.

You can display HTML, CSS, and JS in WebView2 by setting the source URL to display a webpage, as shown in the basic example of loading web content.

Here are some ways to display content in WebView2:

  • Load HTML, CSS, and JS by setting the source URL
  • Load web pages by specifying a URL or loading HTML content directly
  • Customize the web experience by controlling size, visibility, and user interaction settings

Integration and Configuration

You can integrate WebView2 into your C# project by adding the Microsoft.Web.WebView2 NuGet package.

To configure WebView2, you need to create an instance of the WebView2 class and set its configuration options, such as the initial zoom level and the user agent string.

The WebView2 class provides several methods to control the browser's behavior, including the ability to navigate to a specific URL, execute JavaScript, and get the current page's content.

You can also use the WebView2 class to handle events, such as the navigation started and completed events.

Intriguing read: Youtube U N B L O C K

IronPDF Integration

Credit: youtube.com, WebView2 C# - Transfer data from WebView to Winform

IronPDF is a powerful tool for converting HTML to PDF, preserving the original layouts and styles with precision.

It specializes in converting HTML files, URLs, and even raw HTML strings into high-quality PDF files. This capability is especially useful for generating PDFs from web-based content like reports, invoices, and documentation.

By integrating IronPDF with WebView2, developers can create applications that not only display web content but also provide functionality to convert web content to PDF documents.

The combination of WebView2 and IronPDF opens up exciting possibilities for developers working on C# projects.

To add the PDF conversion feature to your application, introduce a button labeled "Convert to PDF" that triggers the conversion process when clicked.

Here's a step-by-step approach to implementing the conversion logic:

  1. Capture the current content from the WebView2 control, which could be the URL or directly the HTML content.
  2. Use IronPDF to create a PDF from the captured web content, rendering the current webpage into a PDF document.
  3. Save the generated PDF to a predefined location or prompt the user to choose a save location, and notify the user of the successful conversion through a message box.

System Requirements

To develop and run C# WebView2 apps, you need to ensure your environment meets the system requirements.

WebView2 apps can run on various Windows operating systems, including Windows 10 SAC 1709 and later, Windows 11, and Windows 11 Enterprise multi-session.

Credit: youtube.com, WebView2 Runtime Error

The supported Windows versions for WebView2 are the same as those supported by Microsoft Edge. For more information, see Microsoft Edge supported Operating Systems.

Here are the specific Windows Client versions that support WebView2 apps:

  • Windows 10 SAC 1709 and later
  • Windows 10 Enterprise 2015 LTSC
  • Windows 10 Enterprise 2016 LTSC
  • Windows 10 Enterprise 2019 LTSC
  • Windows 10 Enterprise 2021 LTSC
  • Windows 10 Enterprise multi-session
  • Windows 10 IoT Enterprise SAC
  • Windows 10 IoT Enterprise 2019 LTSC
  • Windows 10 IoT Enterprise 2021 LTSC
  • Windows 11
  • Windows 11 Enterprise multi-session
  • Windows 11 IoT Enterprise 2024 LTSC

WebView2 apps can also run on various Windows Server versions, including Windows Server 2016 (LTSC), Windows Server 2019 (LTSC), Windows Server 2022 (LTSC), and Windows Server (SAC).

Distributing and Benefits

Distributing a C# WebView2 app requires distributing the WebView2 Runtime along with your app. This will automatically install the runtime onto user machines.

To distribute the WebView2 Runtime, you'll need to follow the instructions in the "Distribute your app and the WebView2 Runtime" section.

The WebView2 Runtime is essential for a seamless user experience, and it's great to know that Microsoft provides support and adds new feature requests on supported platforms.

Here are the key benefits of using C# WebView2:

  • Web ecosystem and skill set: Utilize the entire web platform, libraries, tooling, and talent that exists within the web ecosystem.
  • Rapid innovation: Web development allows for faster deployment and iteration.
  • Windows 10 and 11 support: Support for a consistent user experience across Windows 10 and Windows 11.
  • Native capabilities: Access the full set of Native APIs.
  • Code-sharing: Add web code to your codebase allows for increased reuse across multiple platforms.
  • Microsoft support: Microsoft provides support and adds new feature requests on supported platforms.
  • Evergreen distribution: Rely on an up-to-date version of Chromium with regular platform updates and security patches.
  • Fixed Version distribution: Optionally package a specific version of the Chromium bits in your app.
  • Incremental adoption: Add web components piece-by-piece to your app.

Clone or Download Repo

To clone or download the WebView2Samples repo, you can follow these steps. Create a new project in Visual Studio starting from a project template, using the steps in the sections below. This will give you the latest code and project structure.

Credit: youtube.com, Git - How to clone a project / How to download a project to your computer

You can also clone or download the WebView2Samples repo, which is available in the WebView2Samples repo directory WinForms_GettingStarted. A completed version of this tutorial project is available in the repo, which you can use to understand creating the WinForms project and added WebView2 code.

The sample in the repo might not be as up-to-date as a project that you create by using the latest Visual Studio project templates.

Distributing a App

Distributing a App is a crucial step in making your app available to users. You'll need to distribute the WebView2 Runtime along with your app, which will then be automatically installed onto user machines.

If you're planning to distribute your app, you'll want to know that the WebView2 Runtime is a necessary component. For more information, see the Distribute your app and the WebView2 Runtime section.

Distributing the WebView2 Runtime with your app is a straightforward process. You'll just need to follow the instructions outlined in the Distribute your app and the WebView2 Runtime section.

Readers also liked: What Is Edge Webview2

Benefits

A smiling adult man using a desktop computer at a desk, creating a positive work environment.
Credit: pexels.com, A smiling adult man using a desktop computer at a desk, creating a positive work environment.

Using WebView2 in your app comes with numerous benefits. You can tap into the entire web platform, libraries, tooling, and talent that exists within the web ecosystem.

One of the most significant advantages is the rapid innovation it allows. Web development enables faster deployment and iteration, making it easier to adapt to changing user needs.

WebView2 also supports a consistent user experience across Windows 10 and Windows 11. This means you can create a seamless experience for your users regardless of the Windows version they're using.

You can access the full set of Native APIs with WebView2. This gives you the flexibility to use the features and functionality of the underlying operating system.

Another benefit is code-sharing. By adding web code to your codebase, you can increase reuse across multiple platforms.

Microsoft provides support for WebView2, including adding new feature requests on supported platforms. This ensures you have a reliable partner to help you navigate any challenges you may face.

A young man with glasses drinks soda while working on his computer in a vintage office setting.
Credit: pexels.com, A young man with glasses drinks soda while working on his computer in a vintage office setting.

WebView2 also offers an evergreen distribution, relying on an up-to-date version of Chromium with regular platform updates and security patches. This keeps your app secure and up-to-date with the latest features.

You can optionally package a specific version of the Chromium bits in your app. This gives you more control over the version of the engine your app uses.

WebView2 also supports incremental adoption, allowing you to add web components piece-by-piece to your app. This makes it easier to integrate web technology into your existing app without disrupting the user experience.

Sequence of Samples

To get started with C# WebView2, you'll need to follow a specific sequence of steps. First, install Visual Studio, along with the preview channels of Microsoft Edge, and clone the WebView2Samples repo.

Here's a step-by-step guide to help you get started:

  1. Install and run the main sample.
  2. Install and run the sample for your target platform, if it's a platform other than Win32.
  3. Install and run the finished Getting Started tutorial for your target platform (if the finished project is provided).
  4. Do the Getting Started steps to add WebView2 code to the Visual Studio starter project for your platform.

Some samples might require updating an SDK, so be sure to check the article for each sample for specific instructions.

Introduction and Basics

Credit: youtube.com, WPF C# WebView2 (MS Chromium thing)

WebView2 is a significant advancement in embedding web content within C# applications. It's powered by the Chromium-based Microsoft Edge browser.

This technology enables developers to incorporate the full spectrum of the modern web into their Windows applications. The result is enhanced performance, compatibility, and functionality.

WebView2 is a control to embed in WinForms, making it easy to integrate web content into C# applications. It's a straightforward process that doesn't require extensive coding knowledge.

The Chromium-based Microsoft Edge browser is at the heart of WebView2, providing a robust and reliable platform for web content. This ensures a seamless user experience and fast loading times.

Methods and Properties

The WebView2 control in C# has a variety of properties and methods that make it easy to work with. You can use the Source property to set the URI of the top level document of the WebView2, which is equivalent to calling Navigate(String). If the underlying CoreWebView2 is not yet initialized, setting the Source will trigger initialization.

Credit: youtube.com, How to Properly Initialize WebView2 in WPF ViewModel

The CanGoBack and CanGoForward properties are useful for determining whether the webview can navigate to a previous or next page in the navigation history. These properties are equivalent to the CanGoBack and CanGoForward methods, which navigate to the previous or next page in the navigation history.

Here is a list of some of the key methods of the WebView2 control:

  • GoBack(): navigates to the previous page in navigation history.
  • GoForward(): navigates to the next page in navigation history.
  • Reload(): reloads the top level document of the WebView2.
  • Stop(): stops any in progress navigation in the WebView2.
  • NavigateToString(String): renders the provided HTML as the top level document of the WebView2.

Properties

The Properties section is where you can find the essential characteristics of the WebView2 control. The AllowDrop property determines whether external drops are enabled or disabled.

The CanGoBack property returns true if the webview can navigate to a previous page in the navigation history via the GoBack() method. This property is false if the underlying CoreWebView2 is not yet initialized.

The CanGoForward property returns true if the webview can navigate to a next page in the navigation history via the GoForward() method. This property is also false if the underlying CoreWebView2 is not yet initialized.

Credit: youtube.com, C# Programming Tutorial 19 - Creating Basic Classes, Methods, and Properties

The CoreWebView2 property provides access to the underlying CoreWebView2, which can be used to perform more operations on the WebView2 content than is exposed on the WebView2. This value is null until it is initialized and the object itself has undefined behavior once the control is disposed.

The Source property is the URI of the top level document of the WebView2. Setting the Source is equivalent to calling Navigate(String) and will trigger initialization of the CoreWebView2, if not already initialized. The default value of Source is null, indicating that the CoreWebView2 is not yet initialized.

The ZoomFactor property determines the zoom factor for the WebView.

Remarks

The WebView2 control is a wrapper around the WebView2 COM API, giving you direct access to the underlying ICoreWebView2 interface and its functionality. This means you can use the control's methods and properties to interact with the web view.

Upon creation, the control's CoreWebView2 property will be null, so you'll need to initialize it before using it. You can do this by calling the EnsureCoreWebView2Async method, passing in a CoreWebView2Environment object, or by setting the Source property, which is referred to as implicit initialization.

From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio
Credit: pexels.com, From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio

Explicit initialization involves calling the EnsureCoreWebView2Async method, which starts the initialization process in the background and returns to the caller without waiting for it to finish. This method returns a Task that will complete once the initialization is finished.

To specify options regarding the initialization process, you can pass your own CoreWebView2Environment object to the EnsureCoreWebView2Async method or set the control's CreationProperties property prior to initialization.

Here are the steps that occur after initialization has finished:

1. The control's CoreWebView2InitializationCompleted event is invoked.

2. If a Uri has been set to the Source property, the control will start navigating to it in the background.

3. The Task returned from EnsureCoreWebView2Async will complete.

Some accelerator key presses, like Ctrl+P, will fire standard key press events such as OnKeyDown. To suppress the control's default implementation of an accelerator key press, you can set the Handled property of its EventArgs to true. However, be aware that the underlying browser process is blocked while these handlers execute, so you should avoid doing a lot of work in these handlers and be cautious when invoking WebView2 and CoreWebView2 APIs.

Events and Actions

Credit: youtube.com, How to Pass Parameters to an EventHandler in WebView2

You can subscribe to various events in WebView2, such as NavigationStarting, SourceChanged, and ContentLoading. These events are triggered at different stages of navigation, including when a new navigation starts, the source property changes, and content begins to load.

To handle these events, you can use the CoreWebView2 control's event handlers. For example, you can register a handler for NavigationStarting to cancel any requests not using HTTPS. This is useful for controlling the navigation process and ensuring that sensitive data is not exposed.

Navigation events are essential for building a robust WebView2 application. Here are some common navigation events and their descriptions:

You can also handle other events, such as AcceleratorKeyPressed, which is triggered when an accelerator key is pressed. By handling this event, you can suppress the default handling of the accelerator key and take custom actions instead.

Credit: youtube.com, How to send data to webview2 using C#

To communicate between the loaded website and the Form, you can use the WebMessageReceived event. This event is triggered when web content sends a message to the app host via chrome.webview.postMessage. You can handle this event to display the message in a MessageBox.

In addition to WebMessageReceived, you can also use the CoreWebView2.PostWebMessageAsString method to send a message from the Form to the website. This method allows you to send a string message to the website, which can then be handled using JavaScript.

Frequently Asked Questions

What is WebView2 in Winform?

WebView2 is a browser control for Windows Forms applications, allowing you to embed web content within your WinForms project. To get started, use the C# Windows Forms App (.NET Framework) Visual Studio project template and install the Microsoft.Web.WebView2 SDK package.

Gilbert Deckow

Senior Writer

Gilbert Deckow is a seasoned writer with a knack for breaking down complex technical topics into engaging and accessible content. With a focus on the ever-evolving world of cloud computing, Gilbert has established himself as a go-to expert on Azure Storage Options and related topics. Gilbert's writing style is characterized by clarity, precision, and a dash of humor, making even the most intricate concepts feel approachable and enjoyable to read.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.