Share via


WebView2 Class

Definition

A control to embed web content in a WPF application.

public class WebView2 : System.Windows.Interop.HwndHost
public class WebView2 : System.Windows.Interop.HwndHost, Microsoft.Web.WebView2.Wpf.IWebView2
public class WebView2 : System.Windows.Interop.HwndHost, IDisposable, Microsoft.Web.WebView2.Wpf.IWebView2
type WebView2 = class
    inherit HwndHost
type WebView2 = class
    inherit HwndHost
    interface IWebView2
type WebView2 = class
    inherit HwndHost
    interface IWebView2
    interface IDisposable
Public Class WebView2
Inherits HwndHost
Public Class WebView2
Inherits HwndHost
Implements IWebView2
Public Class WebView2
Inherits HwndHost
Implements IDisposable, IWebView2
Inheritance
WebView2
Implements

Remarks

This control is effectively a wrapper around the WebView2 COM API. You can directly access the underlying ICoreWebView2 interface and all of its functionality by accessing the CoreWebView2 property. Some of the most common COM functionality is also accessible directly through wrapper methods/properties/events on the control.

Upon creation, the control's CoreWebView2 property will be null. This is because creating the CoreWebView2 is an expensive operation which involves things like launching Edge browser processes. There are two ways to cause the CoreWebView2 to be created:

When initialization has finished (regardless of how it was triggered or whether it succeeded) then the following things will occur, in this order:

  1. The control's CoreWebView2InitializationCompleted event will be invoked. If you need to perform one time setup operations on the CoreWebView2 prior to its use then you should do so in a handler for that event.
  2. If initialization was successful and a Uri has been set to the Source property then the control will start navigating to it in the background (i.e. these steps will continue without waiting for the navigation to finish).
  3. The Task returned from EnsureCoreWebView2Async(CoreWebView2Environment, CoreWebView2ControllerOptions) will complete.

For more details about any of the methods/properties/events involved in the initialization process, see its specific documentation.

Because the control's CoreWebView2 is a very heavyweight object (potentially responsible for multiple running processes and megabytes of disk space) the control implements IDisposable to provide an explicit means to free it. Calling Dispose(Boolean) will release the CoreWebView2 and its underlying resources (except any that are also being used by other WebViews), and reset CoreWebView2 to null. After Dispose(Boolean) has been called the CoreWebView2 cannot be re-initialized, and any attempt to use functionality which requires it will throw an ObjectDisposedException.

Accelerator key presses (e.g. Ctrl+P) that occur within the control will fire standard key press events such as OnKeyDown. You can suppress the control's default implementation of an accelerator key press (e.g. printing, in the case of Ctrl+P) by setting the Handled property of its EventArgs to true. Also note that the underlying browser process is blocked while these handlers execute, so:

  1. You should avoid doing a lot of work in these handlers.
  2. Some of the WebView2 and CoreWebView2 APIs may throw errors if invoked within these handlers due to being unable to communicate with the browser process.
If you need to do a lot of work and/or invoke WebView2 APIs in response to accelerator keys then consider kicking off a background task or queuing the work for later execution on the UI thread.

Note that this control extends HwndHost in order to embed windows which live outside of the WPF ecosystem. This has some implications regarding the control's input and output behavior as well as the functionality it "inherits" from UIElement and FrameworkElement.

See the HwndHost and WPF/Win32 interop documentation for more information.

Constructors

WebView2()

Creates a new instance of a WebView2 control. Note that the control's CoreWebView2 will be null until initialized. See the WebView2 class documentation for an initialization overview.

Fields

AllowExternalDropProperty

The WPF DependencyProperty which backs the AllowExternalDropProperty property.

CanGoBackProperty

The WPF DependencyProperty which backs the CanGoBack property.

CanGoForwardProperty

The WPF DependencyProperty which backs the CanGoForward property.

CreationPropertiesProperty

The WPF DependencyProperty which backs the CreationProperties property.

DefaultBackgroundColorProperty

The WPF DependencyProperty which backs the DefaultBackgroundColor property.

DesignModeForegroundColorProperty

The WPF DependencyProperty which backs the DesignModeForegroundColor property.

SourceProperty

The WPF DependencyProperty which backs the Source property.

ZoomFactorProperty

The WPF DependencyProperty which backs the ZoomFactor property.

Properties

AllowExternalDrop

The AllowExternalDrop property for the WebView. This property directly exposes AllowExternalDrop, see its documentation for more info. Getting this property before the CoreWebView2Controller has been initialized will retrieve the last value which was set to it, or true (the default) if none has been. The most recent value set to this property before CoreWebView2Controller has been initialized will be set on it after initialization.

CanGoBack

Returns true if the WebView can navigate to a previous page in the navigation history. Wrapper around the CanGoBack property of CoreWebView2. If CoreWebView2 isn't initialized yet then returns false.

CanGoForward

Returns true if the WebView can navigate to a next page in the navigation history. Wrapper around the CanGoForward property of CoreWebView2. If CoreWebView2 isn't initialized yet then returns false.

ContextMenu
CoreWebView2

Accesses the complete functionality of the underlying CoreWebView2 COM API. Returns null until initialization has completed. See the WebView2 class documentation for an initialization overview.

CreationProperties

Gets or sets a bag of options which are used during initialization of the control's CoreWebView2. Setting this property will not work after initialization of the control's CoreWebView2 has started (the old value will be retained). See the WebView2 class documentation for an initialization overview.

DefaultBackgroundColor

The default background color for the WebView. This property directly exposes DefaultBackgroundColor, see its documentation for more info. Getting this property before the CoreWebView2Controller has been initialized will retrieve the last value which was set to it, or Color.White (the default) if none has been. The most recent value set to this property before CoreWebView2Controller has been initialized will be set on it after initialization.

DesignModeForegroundColor

The foreground color to be used in design mode.

Effect
FocusVisualStyle
InputScope
IsInDesignMode

True when we're in design mode and shouldn't create an underlying CoreWebView2.

Opacity
OpacityMask
Source

The top-level Uri which the WebView is currently displaying (or will display once initialization of its CoreWebView2 is finished). Generally speaking, getting this property is equivalent to getting the Source property and setting this property (to a different value) is equivalent to calling the Navigate(String) method.

ZoomFactor

The zoom factor for the WebView. This property directly exposes ZoomFactor, see its documentation for more info. Getting this property before the CoreWebView2 has been initialized will retrieve the last value which was set to it, or 1.0 (the default) if none has been. The most recent value set to this property before the CoreWebView2 has been initialized will be set on it after initialization.

Methods

BeginInit()

Implementation of the ISupportInitialize pattern. Prevents the control from implicitly initializing its CoreWebView2 until EndInit() is called. Does not prevent explicit initialization of the CoreWebView2 (i.e. EnsureCoreWebView2Async(CoreWebView2Environment, CoreWebView2ControllerOptions)). Mainly intended for use by interactive UI designers.

BuildWindowCore(HandleRef)

This is overridden from HwndHost and is called to instruct us to create our HWND.

DestroyWindowCore(HandleRef)

This is overridden from HwndHost and is called to instruct us to destroy our HWND.

Dispose(Boolean)

This is called by our base class according to the typical implementation of the IDisposable pattern. We implement it by releasing all of our underlying COM resources, including our CoreWebView2.

EndInit()

Implementation of the ISupportInitialize pattern. Invokes any functionality that has been delayed since the corresponding call to BeginInit(). Mainly intended for use by interactive UI designers.

EnsureCoreWebView2Async(CoreWebView2Environment, CoreWebView2ControllerOptions)

Explicitly triggers initialization of the control's CoreWebView2. See the WebView2 class documentation for an initialization overview.

EnsureCoreWebView2Async(CoreWebView2Environment)

Explicitly triggers initialization of the control's CoreWebView2. See the WebView2 class documentation for an initialization overview.

ExecuteScriptAsync(String)

Executes JavaScript code from the javaScript parameter in the current top level document rendered in the WebView. Equivalent to calling ExecuteScriptAsync(String).

GoBack()

Navigates the WebView to the previous page in the navigation history. Equivalent to calling GoBack() If CoreWebView2 hasn't been initialized yet then does nothing.

GoForward()

Navigates the WebView to the next page in the navigation history. Equivalent to calling GoForward(). If CoreWebView2 hasn't been initialized yet then does nothing.

HasFocusWithinCore()

This is overridden from HwndHost and is called when WPF needs to know if the focus is in our control/window. WPF can't know on its own since we're hosting a non-WPF window, so instead it asks us by calling this. To answer, we just track state based on CoreWebView2 events that fire when it gains or loses focus.

NavigateToString(String)

Initiates a navigation to htmlContent as source HTML of a new document. Equivalent to calling NavigateToString(String).

OnGotFocus(RoutedEventArgs)

We override the OnGotFocus(RoutedEventArgs) to prevent the focus event from propagating. We expect the event raised from Microsoft.Web.WebView2.Wpf.WebView2Base.CoreWebView2Controller_GotFocus(System.Object,System.Object)

OnGotKeyboardFocus(KeyboardFocusChangedEventArgs)

This is overridden from UIElement and is called to inform us when we receive the keyboard focus. We handle this by passing the keyboard focus on to the underlying CoreWebView2. We never want to land in a state where our window (this.Handle) actually has the keyboard focus.

OnKeyDown(KeyEventArgs)

This is overridden from UIElement and called to allow us to handle key press input. WPF should never actually call this in response to keyboard events because we're hosting a non-WPF window. When our window has focus Windows will send the input directly to it rather than to WPF's top-level window and input system. This override should only be called when we're explicitly forwarding accelerator key input from the CoreWebView2 to WPF (in CoreWebView2Controller_AcceleratorKeyPressed). Even then, this KeyDownEvent is only triggered because our PreviewKeyDownEvent implementation explicitly triggers it, matching WPF's usual system. So the process is:

  1. CoreWebView2Controller_AcceleratorKeyPressed
  2. PreviewKeyDownEvent
  3. KeyDownEvent
  4. OnKeyDown
.
OnKeyUp(KeyEventArgs)

See OnKeyDown(KeyEventArgs).

OnLostFocus(RoutedEventArgs)

We override the OnLostFocus(RoutedEventArgs) to prevent the focus event from propagating. We expect the event raised from Microsoft.Web.WebView2.Wpf.WebView2Base.CoreWebView2Controller_LostFocus(System.Object,System.Object)

OnPreviewKeyDown(KeyEventArgs)

This is the "Preview" (i.e. tunneling) version of OnKeyDown(KeyEventArgs), so it actually happens first. Like OnKeyDown, this will only ever be called if we're explicitly forwarding key presses from the CoreWebView2. In order to mimic WPF's standard input handling, when we receive this we turn around and fire off the standard bubbling KeyDownEvent. That way others in the WPF tree see the same standard pair of input events that WPF itself would have triggered if it were handling the key press.

OnPreviewKeyUp(KeyEventArgs)

See OnPreviewKeyDown(KeyEventArgs).

OnRender(DrawingContext)

Override for painting to draw

OnWindowPositionChanged(Rect)

This is overridden from HwndHost and called when our control's location has changed. The HwndHost takes care of updating the HWND we created. What we need to do is move our CoreWebView2 to match the new location.

Reload()

Reloads the current page. Equivalent to calling Reload().

Stop()

Stops all navigations and pending resource fetches. Equivalent to calling Stop().

TabIntoCore(TraversalRequest)

This is overridden from HwndHost and is called to inform us that tabbing has caused the focus to move into our control/window. Since WPF can't manage the transition of focus to a non-WPF HWND, it delegates the transition to us here. So our job is just to place the focus in our external HWND.

WndProc(IntPtr, Int32, IntPtr, IntPtr, Boolean)

This is overridden from HwndHost and is called to provide us with Win32 messages that are sent to our hwnd.

Events

AcceleratorKeyPressed

AcceleratorKeyPressed dispatches when an accelerator key is pressed and before it gets handled by the WebView2. You can write a custom handler to suppress handling by the Webview by doing e.Handled = true;.

ContentLoading

A wrapper around the ContentLoading. The only difference between this event and ContentLoading is the first parameter that's passed to handlers. Handlers of this event will receive the WebView2 control, whereas handlers of ContentLoading will receive the CoreWebView2 instance.

CoreWebView2InitializationCompleted

This event is triggered either

  1. when the control's CoreWebView2 has finished being initialized (regardless of how initialization was triggered) but before it is used for anything, or
  2. if the initialization failed. You should handle this event if you need to perform one time setup operations on the CoreWebView2 which you want to affect all of its usages. (e.g. adding event handlers, configuring settings, installing document creation scripts, adding host objects). See the WebView2 class documentation for an initialization overview.
CoreWebView2Ready

This event is triggered when the control's CoreWebView2 has finished being initialized (regardless of how initialization was triggered) but before it is used for anything. You should handle this event if you need to perform one time setup operations on the CoreWebView2 which you want to affect all of its usages (e.g. adding event handlers, configuring settings, installing document creation scripts, adding host objects). See the WebView2 class documentation for an initialization overview.

NavigationCompleted

A wrapper around the NavigationCompleted. The only difference between this event and NavigationCompleted is the first parameter that's passed to handlers. Handlers of this event will receive the WebView2 control, whereas handlers of NavigationCompleted will receive the CoreWebView2 instance.

NavigationStarting

A wrapper around the NavigationStarting. The only difference between this event and NavigationStarting is the first parameter that's passed to handlers. Handlers of this event will receive the WebView2 control, whereas handlers of NavigationStarting will receive the CoreWebView2 instance.

SourceChanged

A wrapper around the SourceChanged. The only difference between this event and SourceChanged is the first parameter that's passed to handlers. Handlers of this event will receive the WebView2 control, whereas handlers of SourceChanged will receive the CoreWebView2 instance.

WebMessageReceived

A wrapper around the WebMessageReceived. The only difference between this event and WebMessageReceived is the first parameter that's passed to handlers. Handlers of this event will receive the WebView2 control, whereas handlers of WebMessageReceived will receive the CoreWebView2 instance.

ZoomFactorChanged

The event is raised when the ZoomFactor property changes. This event directly exposes ZoomFactorChanged.

Applies to

See also