- Application Initialization Overview Application initialization also enables you to enhance the user experience during initialization by redirecting a request to static pages, such as a placeholder or splash screen. Once the site is loaded, it will stop mapping the managed request to the static page, and will start serving the dynamic content. When using the remapManagedRequestsTo attribute in the element, you can only map the managed request to a single page. However, application initialization can be used in conjunction with the out-of-band IIS Url Rewrite module to support more complex handling of placeholder content, including complex mappings to pre-generated static content. In addition to application initialization, you can enable the initialization process to start whenever the application pool is started. You do so by setting the preLoadEnabled attribute in the element to «true». For this to occur, the start mode in the element must be set to AlwaysRunning. Compatibility Setup To support application initialization on your Web server, you must install the Application Initialization role or feature. Windows Server 2012 or Windows Server 2012 R2 On the taskbar, click Server Manager. In Server Manager, click the Manage menu, and then click Add Roles and Features. In the Add Roles and Features wizard, click Next. Select the installation type and click Next. Select the destination server and click Next. On the Server Roles page, expand Web Server (IIS), expand Web Server, expand Application Development, and then select Application Initialization. Click Next. . On the Select Features page, click Next. On the Confirm installation selections page, click Install. On the Results page, click Close. Windows 8 or Windows 8.1 On the Start screen, move the pointer all the way to the lower left corner, right-click the Start button, and then click Control Panel. In Control Panel, click Programs and Features, and then click Turn Windows features on or off. Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then select Application Initialization. Click OK. Click Close. How To How to configure application initialization Open Internet Information Services (IIS) Manager: If you are using Windows Server 2012 or later: On the taskbar, click Server Manager, click Tools, and then click Internet Information Services (IIS) Manager. If you are using Windows 8 or later: Hold down the Windows key, press the letter X, and then click Control Panel. Click Administrative Tools, and then double-click Internet Information Services (IIS) Manager. In the Connections pane, select the server, or expand the server, expand Sites, and then select a site. In the Home pane, double-click the Configuration Editor feature. If you selected a site, select Web.config in the From text box, and then select system.webServer/applicationInitialization in the Section text box. If you selected the server, select system.webServer/applicationInitialization in the Section text box. To specify the name of a static file to be returned during initialization, set remapManagedRequestsTo to the name of the file. If you do not want to load managed modules, set skipManagedModules to true. To specify that the initialization process is initiated automatically whenever an application restart occurs, set doAppInitAfterRestart to true. To specify the application or applications to be initialized upon application restart, click the (Collection) line and then click the ellipsis. In the Collection Editor, to add an application to be initialized, click Add, click hostName, and then set hostName to the name of the host. Click initializationPage and set it to a URL for the application. Close the dialog box. Click Apply in the Actions pane. Configuration Attributes Attribute Description doAppInitAfterRestart Optional Boolean attribute. Specifies that the initialization process is initiated automatically whenever an application restart occurs. Note that this is different than the preLoadEnabled attribute in the application element, which specifies that the initialization process is started after a restart of the application pool. The default value is false . remapManagedRequestsTo Optional string attribute. Specifies a page to remap a request to during application initialization. The default value is «» . skipManagedModules Optional Boolean attribute. Specifies whether the managed modules are loaded ( false ) or not loaded ( true ) during initialization. The default value is false . Child Elements Element Description add Optional element. Specifies the application to be initialized upon application restart. Configuration Sample The following sample shows configuration of application initialization. Sample Code The following examples configure for a site. Добавление возможностей веб-браузера в приложение Windows Forms How to add web browser capabilities to a Windows Forms application Элемент управления WebBrowser позволяет добавить в приложение функциональность веб-браузера. With the WebBrowser control, you can add Web browser functionality to your application. По умолчанию он работает как веб-браузер. The control works like a Web browser by default. После загрузки начального URL-адреса путем установки свойства Url можно переходить по гиперссылкам, а также совершать переход вперед и назад по истории навигации с помощью сочетаний клавиш. After you load an initial URL by setting the Url property, you can navigate by clicking hyperlinks or by using keyboard shortcuts to move backward and forward through navigation history. Дополнительные функциональные возможности браузера по умолчанию доступны в контекстном меню, появляющемся при щелчке правой кнопки мыши. By default, you can access additional browser functionality through the right-click shortcut menu. Вы также можете открывать новые документы, сбрасывая их в элемент управления. You can also open new documents by dropping them onto the control. Кроме того, элемент управления WebBrowser имеет несколько свойств, методов и событий, которые можно использовать для реализации возможностей пользовательского интерфейса, аналогичных имеющимся в Internet Explorer. The WebBrowser control also has several properties, methods, and events that you can use to implement user interface features similar to those found in Internet Explorer. В примере кода ниже реализуются адресная строка, стандартные кнопки браузера, меню Файл, строка состояния и строка заголовка, в которой содержится заголовок текущей страницы. The following code example implements an address bar, typical browser buttons, a File menu, a status bar, and a title bar that displays the current page title. Пример Example Компиляция кода Compile the code Для этого примера требуются: This example requires: WebView control for Windows Forms and WPF WebView will eventually be replaced by WebView2 (currently in preview). Thus, the WebView has been deprecated within the Toolkit, but we are working on conveying requirements to the WebView2 team. If you would like to give feedback directly for WebView2, you can do so here on the Edge repository. The WebView control shows web content in your Windows Forms or WPF desktop application. This is one of several wrapped Universal Windows Platform controls that are available for Windows Forms and WPF applications. For more information, see UWP controls in desktop applications. This control uses the Microsoft Edge rendering engine (EdgeHTML) to embed a view that renders richly formatted HTML5 content from a remote web server, dynamically generated code, or content files. If you have feedback about this control, create a new issue in the Microsoft.Toolkit.Win32 repo and leave your comments there. If you prefer to submit your feedback privately, you can send it to XamlIslandsFeedback@microsoft.com. Your insights and scenarios are critically important to us. About WebView controls Here’s where to find the Windows Forms and Windows Presentation Foundation (WPF) versions of the Microsoft Edge WebView control: NuGet Package Namespace Windows Forms Microsoft.Toolkit.Forms.UI.Controls.WebView Microsoft.Toolkit.Forms.UI.Controls WPF Microsoft.Toolkit.Wpf.UI.Controls.WebView Microsoft.Toolkit.Wpf.UI.Controls (You can find additional related types (such as event args classes) in the Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT namespace.) These controls wrap an instance of the WebViewControl class, and they provide a subset of members from that class. The WebViewControl is similar to the WebView class, but it is designed to run out of process in a desktop application (such as a WPF or Windows Forms application) and it supports a smaller set of members. Unless specified otherwise in this article, the documentation for the WebViewControl class applies to the WPF and Windows Forms WebView controls. This article links to reference pages for the UWP WebViewControl class for more information about most members. Prerequisites вњ”пёЏ Visual Studio 2017. вњ”пёЏ Windows 10 Insider Preview Build 17110 or a later release. вњ”пёЏ .NET Framework 4.6.2 or a later release. вњ”пёЏ Configure your application for high DPI support. To learn how, see this section of the guide. Feature limitations When compared to the UWP WebView control, the current release of the WPF and Windows Forms WebView control has some limitations. For the complete list of these limitations, see Known Issues of the WebView control for Windows Forms and WPF applications. See also the FAQs section below for answers to common questions when WebView for Windows Forms and WPF applications. Add the WebView control to the Visual Studio Toolbox for Windows Forms applications For Visual Studio 15.8 and later: Open the Toolbox in Visual Studio. The WebView control appears in the General section of the Toolbox and you can drag it directly the designer. For earlier versions of Visual Studio: Open the Toolbox in Visual Studio, right-click anywhere in the toolbox, and select the Choose Items option. In the .NET Framework Components tab of the Choose Toolbox Items dialog box, click Browse to locate the Microsoft.Toolkit.Forms.UI.Controls.WebView.dll in your NuGet package folder. Add Microsoft.Toolkit.Forms.UI.Controls.WebView.dll to the list of Toolbox controls, and then close the Choose Toolbox Items dialog box. The WebView control appears in the General section of the Toolbox. In Solution Explorer, the Microsoft.Toolkit.Forms.UI.Controls.WebView assembly appears in the References list. Add the WebView control to the Visual Studio Toolbox for WPF applications Open the Toolbox in Visual Studio or Blend. The WebView control appears in the Windows Community Toolkit section of the Toolbox and you can drag it directly the designer. You can also create an instance of the WebView control in code, but we recommend that you do not add WebView controls to popup windows because support for that scenario will soon be disabled for security reasons. Enable the WebView control to appear properly on high DPI displays If users open your application on displays that have a high Dots Per Inch (DPI) displays, your WebView won’t appear at the proper scale unless you configure your application first. Configure a Windows Forms application Configure a WPF application Add the following XML to your application manifest file: Add the following XML to your application configuration file: Modify the appearance of a WebView To constrain the display area, set the Width and Height properties. This table contains links to each of these members. Member Windows Forms WebView WPF WebView Width property Width Width Height property Height Height Get the web page title You can get the title of the HTML document currently displayed in the WebView by using the DocumentTitle property. Input events and tab order You can use the InvokeScriptAsync method with the JavaScript eval function to use the HTML event handlers, and use window.external.notify from the HTML event handlers to notify the application using the ScriptNotify event. Navigate to content The WebView control has several APIs for basic navigation: GoBack, GoForward, Stop, Refresh, CanGoBack, and CanGoForward. You can use these to add typical web browsing capabilities to your app. To set the initial content of the the WebView control, you can set the Source property in code, XAML, or in the Properties window. You can also use the Navigate methods to load content in code. Here’s an example. If calling Navigate() in code, you must wait until the control has loaded for the operation to complete successfully. Respond to navigation events The WebView control provides several events that you can use to respond to navigation and content loading states. The events occur in the following order for the root web view content: The NavigationStarting event is raised before the web view navigates to new content. You can cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.Cancel property to true. The ContentLoading is raised when the web view has started loading new content. The DOMContentLoaded event is raised when the web view has finished parsing the current HTML content. The NavigationCompleted event is raised when the web view has finished loading the current content or if navigation has failed. To determine whether navigation has failed, check the IsSuccess and WebErrorStatus properties of the event args. Similar events occur in the same order for each iframe in the web view content: The FrameNavigationStarting event is raised before a frame in the web view navigates to new content. The FrameContentLoading event is raised when a frame in the web view has started loading new content. The FrameDOMContentLoaded event is raised when a frame in the web view has finished parsing its current HTML content. The FrameNavigationCompleted event is raised when a frame in the web view has finished loading its content. Respond to potential problems You can respond to potential problems with the content such as long running scripts, content that the WebView control can’t load, and warnings of unsafe content. Your app might appear unresponsive while scripts are running. The LongRunningScriptDetected event is raised periodically while the web view executes JavaScript. This provides you with an opportunity to interrupt the script. To determine how long the script has been running, check the ExecutionTime property of the WebViewControlLongRunningScriptDetectedEventArgs. To halt the script, set the event args StopPageScriptExecution property to true. The halted script will not execute again unless it is reloaded during a subsequent web view navigation. The web view control cannot host arbitrary file types. When an attempt is made to load content that the web view can’t host, the UnviewableContentIdentified event occurs. You can handle this event and notify the user. Similarly, the UnsupportedUriSchemeIdentified event occurs when a URI scheme that’s not supported is invoked in the web content, such as fbconnect:// or mailto://. You can handle this event to provide custom behavior instead of allowing the default system launcher to launch the URI. The UnsafeContentWarningDisplayingEvent event occurs when the web view shows a warning page for content that was reported as unsafe by the SmartScreen Filter. If the user chooses to continue the navigation, subsequent navigation to the page will not display the warning nor fire the event. Handle special cases for web view content You can use the ContainsFullScreenElement property and ContainsFullScreenElementChanged event to detect, respond to, and enable full-screen experiences in web content, such as full-screen video playback. For example, you might use the ContainsFullScreenElementChanged event to resize the web view to occupy the entire app view, or, as the following example illustrates, put a windowed app in full screen mode. You can use the NewWindowRequested event to handle cases where hosted web content requests a new window, such as a popup window. You can use another WebView control to display the contents of the requested window. Handle the PermissionRequested event to enable web features that require special capabilities. These currently include geolocation, IndexedDB storage, and user audio and video (for example, from a microphone or webcam). In addition to the app handling the PermissionRequested event, the user will have to approve standard system dialogs for apps requesting location or media capabilities in order for these features to be enabled. Here is an example of how an app would enable geolocation in a map from Bing: If your app requires user input or other asynchronous operations to respond to a permission request, use the Defer method of WebViewControlPermissionRequest to create a WebViewControlDeferredPermissionRequest that can be acted upon at a later time. Interact with web view content You can interact with the content of the web view by using the InvokeScriptAsync method to invoke or inject script into the web view content, and the ScriptNotify event to get information back from the web view content. To invoke JavaScript inside the web view content, use the InvokeScriptAsync method. The invoked script can return only string values. For example, if the content of a web view named webView1 contains a function named setDate that takes 3 parameters, you can invoke it like this. You can use InvokeScriptAsync with the JavaScript eval function to inject content into the web page. Here, the text of a XAML text box ( nameTextBox.Text ) is written to a div in an HTML page hosted in webView1 . Scripts in the web view content can use window.external.notify with a string parameter to send information back to your app. To receive these messages, handle the ScriptNotify event. Options for web content hosting You can use the Settings property (of type WebViewControlSettings to control whether JavaScript and IndexedDB are enabled. For example, if you use a web view to display strictly static content, you might want to disable JavaScript for best performance. Creating multiple web views in the same process By default, the WebView is hosted outside of your application’s process in a process called WWAHost. When using the designer or default constructor, each new WebView is created in a new WWAHost instance, with its own copy of state. To share session cookies and state, consider using the same WWAHost process to host your WebView. For Windows Forms Applications For example, if through the designer a WebView named webView1 is on Form1 , you can create a new WebView that shares the same process and state with webView1 like this. For WPF Applications Similar to the Windows Forms example, if through the designer a WebView is created named WebView1 on the Window , you can create a new WebView that shares the same process and state with WebView1 like this. Frequently Asked Questions (FAQs) There’s WebBrowser, WebView, and WebViewControl. What’s the difference? When people refer to a “web view” they either refer to the WebBrowser control in .NET, which uses the legacy Internet Explorer «Trident» (MSHTML) engine, the Universal Windows Platform (UWP) WebView which uses the Microsoft Edge (EdgeHTML) engine on some versions of Windows and Trident on others, or the WebViewControl, which is a subset of the UWP WebView available for use in Windows Forms, WPF and other desktop (Win32) applications. Is WebViewControl available on Windows Server? No. Long-Term Servicing Channel (LTSC) versions of Windows, including Windows Server, don’t include Microsoft Edge or many other UWP applications. These apps and their required services are frequently updated with new functionality and cannot be supported on systems running a LTSC operating system. A future workaround might be to use Windows Virtual Desktop to run your WebViewControl application through a virtualized desktop on Windows 7, Windows 10 LTSC versions, and other environments where Microsoft Edge (and the WebViewControl) wouldn’t otherwise be supported. Are there samples? Yes! Samples are available for Windows Forms, Windows Presentation Foundation, and C++ here: https://github.com/rjmurillo/webview-samples Can I simply swap out the Internet Explorer WebBrowser for Microsoft Edge WebViewControl in my application? No, the APIs differ significantly, as the WebViewControl represents several generations of browser development since the IE WebBrowser control was released. Can I inject native objects into my WebViewControl content? No. Neither the WebBrower (Internet Explorer) ObjectForScripting property nor the WebView (UWP) AddWebAllowedObject method are supported in WebViewControl. As a workaround, you can use window.external.notify / ScriptNotify and JavaScript execution to communicate between the layers, for example: https://github.com/rjmurillo/WebView_AddAllowedWebObjectWorkaround Can I host the UWP WebView in WPF or Windows Forms using XAML islands? No. It is not possible to host the (full-featured) UWP WebView using XAML islands due to architectural and security constraints. The WebViewControl provided by Windows Community Toolkit is the recommended way of hosting a modern WebView control in desktop applications.
- Overview
- Compatibility
- Setup
- Windows Server 2012 or Windows Server 2012 R2
- Windows 8 or Windows 8.1
- How To
- How to configure application initialization
- Configuration
- Attributes
- Child Elements
- Configuration Sample
- Sample Code
- Добавление возможностей веб-браузера в приложение Windows Forms How to add web browser capabilities to a Windows Forms application
- Пример Example
- Компиляция кода Compile the code
- WebView control for Windows Forms and WPF
- About WebView controls
- Prerequisites
- Feature limitations
- Add the WebView control to the Visual Studio Toolbox for Windows Forms applications
- Add the WebView control to the Visual Studio Toolbox for WPF applications
- Enable the WebView control to appear properly on high DPI displays
- Configure a Windows Forms application
- Configure a WPF application
- Modify the appearance of a WebView
- Get the web page title
- Input events and tab order
- Navigate to content
- Respond to navigation events
- Respond to potential problems
- Handle special cases for web view content
- Interact with web view content
- Options for web content hosting
- Creating multiple web views in the same process
- For Windows Forms Applications
- For WPF Applications
- Frequently Asked Questions (FAQs)
- There’s WebBrowser, WebView, and WebViewControl. What’s the difference?
- Is WebViewControl available on Windows Server?
- Are there samples?
- Can I simply swap out the Internet Explorer WebBrowser for Microsoft Edge WebViewControl in my application?
- Can I inject native objects into my WebViewControl content?
- Can I host the UWP WebView in WPF or Windows Forms using XAML islands?
Application Initialization Overview
Application initialization also enables you to enhance the user experience during initialization by redirecting a request to static pages, such as a placeholder or splash screen. Once the site is loaded, it will stop mapping the managed request to the static page, and will start serving the dynamic content. When using the remapManagedRequestsTo attribute in the element, you can only map the managed request to a single page. However, application initialization can be used in conjunction with the out-of-band IIS Url Rewrite module to support more complex handling of placeholder content, including complex mappings to pre-generated static content.
In addition to application initialization, you can enable the initialization process to start whenever the application pool is started. You do so by setting the preLoadEnabled attribute in the element to «true». For this to occur, the start mode in the element must be set to AlwaysRunning.
Compatibility
Setup
To support application initialization on your Web server, you must install the Application Initialization role or feature.
Windows Server 2012 or Windows Server 2012 R2
- On the taskbar, click Server Manager.
- In Server Manager, click the Manage menu, and then click Add Roles and Features.
- In the Add Roles and Features wizard, click Next. Select the installation type and click Next. Select the destination server and click Next.
- On the Server Roles page, expand Web Server (IIS), expand Web Server, expand Application Development, and then select Application Initialization. Click Next.
.
- On the Select Features page, click Next.
- On the Confirm installation selections page, click Install.
- On the Results page, click Close.
Windows 8 or Windows 8.1
- On the Start screen, move the pointer all the way to the lower left corner, right-click the Start button, and then click Control Panel.
- In Control Panel, click Programs and Features, and then click Turn Windows features on or off.
- Expand Internet Information Services, expand World Wide Web Services, expand Application Development Features, and then select Application Initialization.
- Click OK.
- Click Close.
How To
How to configure application initialization
Open Internet Information Services (IIS) Manager:
If you are using Windows Server 2012 or later:
- On the taskbar, click Server Manager, click Tools, and then click Internet Information Services (IIS) Manager.
If you are using Windows 8 or later:
- Hold down the Windows key, press the letter X, and then click Control Panel.
- Click Administrative Tools, and then double-click Internet Information Services (IIS) Manager.
In the Connections pane, select the server, or expand the server, expand Sites, and then select a site.
In the Home pane, double-click the Configuration Editor feature.
If you selected a site, select Web.config in the From text box, and then select system.webServer/applicationInitialization in the Section text box.
If you selected the server, select system.webServer/applicationInitialization in the Section text box.
To specify the name of a static file to be returned during initialization, set remapManagedRequestsTo to the name of the file.
If you do not want to load managed modules, set skipManagedModules to true.
To specify that the initialization process is initiated automatically whenever an application restart occurs, set doAppInitAfterRestart to true.
To specify the application or applications to be initialized upon application restart, click the (Collection) line and then click the ellipsis.
In the Collection Editor, to add an application to be initialized, click Add, click hostName, and then set hostName to the name of the host. Click initializationPage and set it to a URL for the application. Close the dialog box.
Click Apply in the Actions pane.
Configuration
Attributes
Attribute | Description |
---|---|
doAppInitAfterRestart | Optional Boolean attribute. |
Specifies that the initialization process is initiated automatically whenever an application restart occurs. Note that this is different than the preLoadEnabled attribute in the application element, which specifies that the initialization process is started after a restart of the application pool.
The default value is false .
Specifies a page to remap a request to during application initialization.
The default value is «» .
Specifies whether the managed modules are loaded ( false ) or not loaded ( true ) during initialization.
The default value is false .
Child Elements
Element | Description |
---|---|
add | Optional element. |
Specifies the application to be initialized upon application restart.
Configuration Sample
The following sample shows configuration of application initialization.
Sample Code
The following examples configure for a site.
Добавление возможностей веб-браузера в приложение Windows Forms How to add web browser capabilities to a Windows Forms application
Элемент управления WebBrowser позволяет добавить в приложение функциональность веб-браузера. With the WebBrowser control, you can add Web browser functionality to your application. По умолчанию он работает как веб-браузер. The control works like a Web browser by default. После загрузки начального URL-адреса путем установки свойства Url можно переходить по гиперссылкам, а также совершать переход вперед и назад по истории навигации с помощью сочетаний клавиш. After you load an initial URL by setting the Url property, you can navigate by clicking hyperlinks or by using keyboard shortcuts to move backward and forward through navigation history. Дополнительные функциональные возможности браузера по умолчанию доступны в контекстном меню, появляющемся при щелчке правой кнопки мыши. By default, you can access additional browser functionality through the right-click shortcut menu. Вы также можете открывать новые документы, сбрасывая их в элемент управления. You can also open new documents by dropping them onto the control. Кроме того, элемент управления WebBrowser имеет несколько свойств, методов и событий, которые можно использовать для реализации возможностей пользовательского интерфейса, аналогичных имеющимся в Internet Explorer. The WebBrowser control also has several properties, methods, and events that you can use to implement user interface features similar to those found in Internet Explorer.
В примере кода ниже реализуются адресная строка, стандартные кнопки браузера, меню Файл, строка состояния и строка заголовка, в которой содержится заголовок текущей страницы. The following code example implements an address bar, typical browser buttons, a File menu, a status bar, and a title bar that displays the current page title.
Пример Example
Компиляция кода Compile the code
Для этого примера требуются: This example requires:
WebView control for Windows Forms and WPF
WebView will eventually be replaced by WebView2 (currently in preview). Thus, the WebView has been deprecated within the Toolkit, but we are working on conveying requirements to the WebView2 team. If you would like to give feedback directly for WebView2, you can do so here on the Edge repository.
The WebView control shows web content in your Windows Forms or WPF desktop application. This is one of several wrapped Universal Windows Platform controls that are available for Windows Forms and WPF applications. For more information, see UWP controls in desktop applications.
This control uses the Microsoft Edge rendering engine (EdgeHTML) to embed a view that renders richly formatted HTML5 content from a remote web server, dynamically generated code, or content files.
If you have feedback about this control, create a new issue in the Microsoft.Toolkit.Win32 repo and leave your comments there. If you prefer to submit your feedback privately, you can send it to XamlIslandsFeedback@microsoft.com. Your insights and scenarios are critically important to us.
About WebView controls
Here’s where to find the Windows Forms and Windows Presentation Foundation (WPF) versions of the Microsoft Edge WebView control:
NuGet Package | Namespace | |
---|---|---|
Windows Forms | Microsoft.Toolkit.Forms.UI.Controls.WebView | Microsoft.Toolkit.Forms.UI.Controls |
WPF | Microsoft.Toolkit.Wpf.UI.Controls.WebView | Microsoft.Toolkit.Wpf.UI.Controls |
(You can find additional related types (such as event args classes) in the Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT namespace.)
These controls wrap an instance of the WebViewControl class, and they provide a subset of members from that class. The WebViewControl is similar to the WebView class, but it is designed to run out of process in a desktop application (such as a WPF or Windows Forms application) and it supports a smaller set of members.
Unless specified otherwise in this article, the documentation for the WebViewControl class applies to the WPF and Windows Forms WebView controls. This article links to reference pages for the UWP WebViewControl class for more information about most members.
Prerequisites
вњ”пёЏ Visual Studio 2017.
вњ”пёЏ Windows 10 Insider Preview Build 17110 or a later release.
вњ”пёЏ .NET Framework 4.6.2 or a later release.
вњ”пёЏ Configure your application for high DPI support. To learn how, see this section of the guide.
Feature limitations
When compared to the UWP WebView control, the current release of the WPF and Windows Forms WebView control has some limitations. For the complete list of these limitations, see Known Issues of the WebView control for Windows Forms and WPF applications.
See also the FAQs section below for answers to common questions when WebView for Windows Forms and WPF applications.
Add the WebView control to the Visual Studio Toolbox for Windows Forms applications
For Visual Studio 15.8 and later:
Open the Toolbox in Visual Studio. The WebView control appears in the General section of the Toolbox and you can drag it directly the designer.
For earlier versions of Visual Studio:
Open the Toolbox in Visual Studio, right-click anywhere in the toolbox, and select the Choose Items option.
In the .NET Framework Components tab of the Choose Toolbox Items dialog box, click Browse to locate the Microsoft.Toolkit.Forms.UI.Controls.WebView.dll in your NuGet package folder.
Add Microsoft.Toolkit.Forms.UI.Controls.WebView.dll to the list of Toolbox controls, and then close the Choose Toolbox Items dialog box.
The WebView control appears in the General section of the Toolbox.
In Solution Explorer, the Microsoft.Toolkit.Forms.UI.Controls.WebView assembly appears in the References list.
Add the WebView control to the Visual Studio Toolbox for WPF applications
Open the Toolbox in Visual Studio or Blend. The WebView control appears in the Windows Community Toolkit section of the Toolbox and you can drag it directly the designer. You can also create an instance of the WebView control in code, but we recommend that you do not add WebView controls to popup windows because support for that scenario will soon be disabled for security reasons.
Enable the WebView control to appear properly on high DPI displays
If users open your application on displays that have a high Dots Per Inch (DPI) displays, your WebView won’t appear at the proper scale unless you configure your application first.
Configure a Windows Forms application
Configure a WPF application
Add the following XML to your application manifest file:
Add the following XML to your application configuration file:
Modify the appearance of a WebView
To constrain the display area, set the Width and Height properties.
This table contains links to each of these members.
Member | Windows Forms WebView | WPF WebView |
---|---|---|
Width property | Width | Width |
Height property | Height | Height |
Get the web page title
You can get the title of the HTML document currently displayed in the WebView by using the DocumentTitle property.
Input events and tab order
You can use the InvokeScriptAsync method with the JavaScript eval function to use the HTML event handlers, and use window.external.notify from the HTML event handlers to notify the application using the ScriptNotify event.
Navigate to content
The WebView control has several APIs for basic navigation: GoBack, GoForward, Stop, Refresh, CanGoBack, and CanGoForward. You can use these to add typical web browsing capabilities to your app.
To set the initial content of the the WebView control, you can set the Source property in code, XAML, or in the Properties window. You can also use the Navigate methods to load content in code. Here’s an example.
If calling Navigate() in code, you must wait until the control has loaded for the operation to complete successfully.
Respond to navigation events
The WebView control provides several events that you can use to respond to navigation and content loading states. The events occur in the following order for the root web view content:
The NavigationStarting event is raised before the web view navigates to new content. You can cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.Cancel property to true.
The ContentLoading is raised when the web view has started loading new content.
The DOMContentLoaded event is raised when the web view has finished parsing the current HTML content.
The NavigationCompleted event is raised when the web view has finished loading the current content or if navigation has failed. To determine whether navigation has failed, check the IsSuccess and WebErrorStatus properties of the event args.
Similar events occur in the same order for each iframe in the web view content:
The FrameNavigationStarting event is raised before a frame in the web view navigates to new content.
The FrameContentLoading event is raised when a frame in the web view has started loading new content.
The FrameDOMContentLoaded event is raised when a frame in the web view has finished parsing its current HTML content.
The FrameNavigationCompleted event is raised when a frame in the web view has finished loading its content.
Respond to potential problems
You can respond to potential problems with the content such as long running scripts, content that the WebView control can’t load, and warnings of unsafe content.
Your app might appear unresponsive while scripts are running. The LongRunningScriptDetected event is raised periodically while the web view executes JavaScript. This provides you with an opportunity to interrupt the script. To determine how long the script has been running, check the ExecutionTime property of the WebViewControlLongRunningScriptDetectedEventArgs. To halt the script, set the event args StopPageScriptExecution property to true. The halted script will not execute again unless it is reloaded during a subsequent web view navigation.
The web view control cannot host arbitrary file types. When an attempt is made to load content that the web view can’t host, the UnviewableContentIdentified event occurs. You can handle this event and notify the user.
Similarly, the UnsupportedUriSchemeIdentified event occurs when a URI scheme that’s not supported is invoked in the web content, such as fbconnect:// or mailto://. You can handle this event to provide custom behavior instead of allowing the default system launcher to launch the URI.
The UnsafeContentWarningDisplayingEvent event occurs when the web view shows a warning page for content that was reported as unsafe by the SmartScreen Filter. If the user chooses to continue the navigation, subsequent navigation to the page will not display the warning nor fire the event.
Handle special cases for web view content
You can use the ContainsFullScreenElement property and ContainsFullScreenElementChanged event to detect, respond to, and enable full-screen experiences in web content, such as full-screen video playback.
For example, you might use the ContainsFullScreenElementChanged event to resize the web view to occupy the entire app view, or, as the following example illustrates, put a windowed app in full screen mode.
You can use the NewWindowRequested event to handle cases where hosted web content requests a new window, such as a popup window. You can use another WebView control to display the contents of the requested window.
Handle the PermissionRequested event to enable web features that require special capabilities. These currently include geolocation, IndexedDB storage, and user audio and video (for example, from a microphone or webcam).
In addition to the app handling the PermissionRequested event, the user will have to approve standard system dialogs for apps requesting location or media capabilities in order for these features to be enabled.
Here is an example of how an app would enable geolocation in a map from Bing:
If your app requires user input or other asynchronous operations to respond to a permission request, use the Defer method of WebViewControlPermissionRequest to create a WebViewControlDeferredPermissionRequest that can be acted upon at a later time.
Interact with web view content
You can interact with the content of the web view by using the InvokeScriptAsync method to invoke or inject script into the web view content, and the ScriptNotify event to get information back from the web view content.
To invoke JavaScript inside the web view content, use the InvokeScriptAsync method. The invoked script can return only string values.
For example, if the content of a web view named webView1 contains a function named setDate that takes 3 parameters, you can invoke it like this.
You can use InvokeScriptAsync with the JavaScript eval function to inject content into the web page.
Here, the text of a XAML text box ( nameTextBox.Text ) is written to a div in an HTML page hosted in webView1 .
Scripts in the web view content can use window.external.notify with a string parameter to send information back to your app. To receive these messages, handle the ScriptNotify event.
Options for web content hosting
You can use the Settings property (of type WebViewControlSettings to control whether JavaScript and IndexedDB are enabled. For example, if you use a web view to display strictly static content, you might want to disable JavaScript for best performance.
Creating multiple web views in the same process
By default, the WebView is hosted outside of your application’s process in a process called WWAHost. When using the designer or default constructor, each new WebView is created in a new WWAHost instance, with its own copy of state. To share session cookies and state, consider using the same WWAHost process to host your WebView.
For Windows Forms Applications
For example, if through the designer a WebView named webView1 is on Form1 , you can create a new WebView that shares the same process and state with webView1 like this.
For WPF Applications
Similar to the Windows Forms example, if through the designer a WebView is created named WebView1 on the Window , you can create a new WebView that shares the same process and state with WebView1 like this.
Frequently Asked Questions (FAQs)
There’s WebBrowser, WebView, and WebViewControl. What’s the difference?
When people refer to a “web view” they either refer to the WebBrowser control in .NET, which uses the legacy Internet Explorer «Trident» (MSHTML) engine, the Universal Windows Platform (UWP) WebView which uses the Microsoft Edge (EdgeHTML) engine on some versions of Windows and Trident on others, or the WebViewControl, which is a subset of the UWP WebView available for use in Windows Forms, WPF and other desktop (Win32) applications.
Is WebViewControl available on Windows Server?
No. Long-Term Servicing Channel (LTSC) versions of Windows, including Windows Server, don’t include Microsoft Edge or many other UWP applications. These apps and their required services are frequently updated with new functionality and cannot be supported on systems running a LTSC operating system.
A future workaround might be to use Windows Virtual Desktop to run your WebViewControl application through a virtualized desktop on Windows 7, Windows 10 LTSC versions, and other environments where Microsoft Edge (and the WebViewControl) wouldn’t otherwise be supported.
Are there samples?
Yes! Samples are available for Windows Forms, Windows Presentation Foundation, and C++ here: https://github.com/rjmurillo/webview-samples
Can I simply swap out the Internet Explorer WebBrowser for Microsoft Edge WebViewControl in my application?
No, the APIs differ significantly, as the WebViewControl represents several generations of browser development since the IE WebBrowser control was released.
Can I inject native objects into my WebViewControl content?
No. Neither the WebBrower (Internet Explorer) ObjectForScripting property nor the WebView (UWP) AddWebAllowedObject method are supported in WebViewControl. As a workaround, you can use window.external.notify / ScriptNotify and JavaScript execution to communicate between the layers, for example: https://github.com/rjmurillo/WebView_AddAllowedWebObjectWorkaround
Can I host the UWP WebView in WPF or Windows Forms using XAML islands?
No. It is not possible to host the (full-featured) UWP WebView using XAML islands due to architectural and security constraints. The WebViewControl provided by Windows Community Toolkit is the recommended way of hosting a modern WebView control in desktop applications.