WebView2CompositionControl Class

Definition

Visual hosting version of the WebView2 control.

[System.Windows.TemplatePart(Name="PART_image", Type=typeof(System.Windows.Controls.Image))]
public class WebView2CompositionControl : System.Windows.Controls.Control, IDisposable, Microsoft.Web.WebView2.Wpf.IWebView2, System.Windows.Interop.IKeyboardInputSink
[<System.Windows.TemplatePart(Name="PART_image", Type=typeof(System.Windows.Controls.Image))>]
type WebView2CompositionControl = class
    inherit Control
    interface IWebView2
    interface IDisposable
    interface IKeyboardInputSink
Public Class WebView2CompositionControl
Inherits Control
Implements IDisposable, IKeyboardInputSink, IWebView2
Inheritance
WebView2CompositionControl
Attributes
Implements

Remarks

This control is effectively a wrapper around the [WebView2 COM API](https://aka.ms/webview2). 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() 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() 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.

This control extends Control in order to host the image displaying WebView's content using template. This has some implications regarding the control's input and output behavior as well as the functionality it "inherits" from UIElement and FrameworkElement.

The content of WebView2CompositionControl is rendered by an Image. By default, UseLayoutRounding of WebView2CompositionControl is set to true. This can prevent the Image from becoming blurry at certain dimensions, but it disables anti-aliasing. Set it to false if you want to keep the anti-aliasing.

Note that the WebView2CompositionControl uses a GraphicsCaptureSession to capture the screen content from the underlying browser processes. As such, you may experience lower framerates compared to the standard WebView2 control, and DRM protected content will fail to play or display properly.

Constructors

WebView2CompositionControl()

Creates a new instance of a WebView2Composition control. Note that the control's CoreWebView2 will be null until initialized. See the WebView2CompositionControl 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.

FpsDividerProperty

The WPF DependencyProperty which backs the Microsoft.Web.WebView2.Wpf.WebView2CompositionControl.FpsDivider 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.

KeyboardInputSite

WebView2Composition Control only needs IKeyboardInputSink:TabInto to get the direction of tab traversal. KeyboardInputSite is not implemented by WebView2Composition.

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.

Dispose()

Implementation of the IDisposable pattern. This will release all of our underlying COM resources.

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.

HasFocusWithin()

IKeyboardInputSink:HasFocusWithin interface. Whether WebView has focus.

NavigateToString(String)

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

OnApplyTemplate()

OnApplyTemplate() interface.

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)

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 the focus is on the controller's HWND. When Controller's HWND has focus, WPF does not know the Controller's HWND belongs to this control, and the key event will not be fired for this control and WPF main window. 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)

OnMnemonic(MSG, ModifierKeys)

IKeyboardInputSink:OnMnemonic interface. Not implemented by WebView2.

OnMouseDoubleClick(MouseButtonEventArgs)

This is an event handler for WPF control's OnMouseDoubleClick event. We use CoreWebView2CompositionController.SendMouseInput to send the input to our browser.

OnMouseDown(MouseButtonEventArgs)

This is an event handler for WPF control's OnMouseDown event. We use CoreWebView2CompositionController.SendMouseInput to send the mouse input to our browser.

OnMouseMove(MouseEventArgs)

This is an event handler for WPF control's OnMouseMove event. We use CoreWebView2CompositionController.SendMouseInput to send the mouse input to our browser.

OnMouseUp(MouseButtonEventArgs)

This is an event handler for WPF control's OnMouseUp event. We use CoreWebView2CompositionController.SendMouseInput to send the mouse input to our browser.

OnMouseWheel(MouseWheelEventArgs)

This is an event handler for WPF control's OnMouseWheel event. We use CoreWebView2CompositionController.SendMouseInput to send the input to our browser.

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

OnTouchDown(TouchEventArgs)

This is an event handler for WPF control's OnTouchDown event. We use CoreWebView2CompositionController.SendPointerInput to send the touch input to our browser.

OnTouchMove(TouchEventArgs)

This is an event handler for WPF control's OnTouchMove event. We use CoreWebView2CompositionController.SendPointerInput to send the touch input to our browser.

OnTouchUp(TouchEventArgs)

This is an event handler for WPF control's OnTouchUp event. We use CoreWebView2CompositionController.SendPointerInput to send the touch input to our browser.

RegisterKeyboardInputSink(IKeyboardInputSink)

IKeyboardInputSink:RegisterKeyboardInputSink interface. Not implemented by WebView2.

Reload()

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

SendMouseInput(CoreWebView2MouseEventKind, CoreWebView2MouseEventVirtualKeys, UInt32, Point)

Send the mouse event to the WebView2 Control.

SendPointerInput(CoreWebView2PointerEventKind, CoreWebView2PointerInfo)

Send the pointer event to the WebView2 Control.

Stop()

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

TabInto(TraversalRequest)

IKeyboardInputSink:TabInto interface.

TranslateAccelerator(MSG, ModifierKeys)

IKeyboardInputSink:TranslateAccelerator interface. Not implemented by WebView2.

TranslateChar(MSG, ModifierKeys)

IKeyboardInputSink:TranslateChar interface. Not implemented by WebView2.

WebView2CompositionControl_LocationChanged(Object, EventArgs)

This is an event handler for WPF control's LocationChange event. We use CoreWebView2Controller.NotifyParentWindowPositionChanged to notify our browser our position has changed.

WebView2CompositionControl_SizeChanged(Object, SizeChangedEventArgs)

This is an event handler for WPF control's SizeChanged event. We use CoreWebView2Controller.NotifyParentWindowPositionChanged to notify our browser our size and relative location has changed.

Events

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.
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