Class CoreWebView2Controller
This class is the owner of the CoreWebView2 object, and provides support for resizing, showing and hiding, focusing, and other functionality related to windowing and composition.
public class CoreWebView2Controller
- Inheritance
-
CoreWebView2Controller
- Inherited Members
Remarks
The CoreWebView2Controller owns the CoreWebView2, and if all references to the CoreWebView2Controller go away, the WebView will be closed.
Properties
AllowExternalDrop
Gets or sets the WebView allow external drop property.
public bool AllowExternalDrop { get; set; }
Property Value
Examples
Remarks
The AllowExternalDrop is to configure the capability that dropping files into webview2 is allowed or permitted. The default value is true.
Bounds
Gets or sets the WebView bounds.
public Rectangle Bounds { get; set; }
Property Value
Remarks
Bounds are relative to the ParentWindow. The app has two ways to position a WebView:
- Create a child HWND that is the WebView parent HWND. Position the window where the WebView should be. Use (0, 0) for the top-left corner (the offset) of the Bounds of the WebView.
- Use the top-most window of the app as the WebView parent HWND. For example, to position ebView correctly in the app, set the top-left corner of the Bounds of the WebView.
The values of Bounds are limited by the coordinate space of the host.
BoundsMode
Gets or sets the WebView bounds mode.
public CoreWebView2BoundsMode BoundsMode { get; set; }
Property Value
Remarks
BoundsMode affects how setting the Bounds and RasterizationScale properties work. Bounds mode can either be in UseRawPixels mode or UseRasterizationScale mode.
CoreWebView2
Gets the CoreWebView2 associated with this CoreWebView2Controller.
public CoreWebView2 CoreWebView2 { get; }
Property Value
- See Also
DefaultBackgroundColor
Gets or sets the WebView default background color.
public Color DefaultBackgroundColor { get; set; }
Property Value
Examples
Remarks
The DefaultBackgroundColor
is the color that renders underneath all web content. This means WebView renders this color when there is no web content loaded such as before the initial navigation or between navigations. This also means web pages with undefined css background properties or background properties containing transparent pixels will render their contents over this color. Web pages with defined and opaque background properties that span the page will obscure the DefaultBackgroundColor
and display normally. The default value for this property is white to resemble the native browser experience. Currently this API only supports opaque colors and transparency. It will fail for colors with alpha values that don't equal 0 or 255 ie. translucent colors are not supported. It also does not support transparency on Windows 7. On Windows 7, setting DefaultBackgroundColor to a Color with an Alpha value other than 255 will result in failure. On any OS above Win7, choosing a transparent color will result in showing hosting app content. This means webpages without explicit background properties defined will render web content over hosting app content.
This property may also be set via the WEBVIEW2_DEFAULT_BACKGROUND_COLOR
environment variable. There is a known issue with background color where just setting the color by property can still leave the app with a white flicker before the DefaultBackgroundColor
property takes effect. Setting the color via environment variable solves this issue. The value must be a hex value that can optionally prepend a 0x. The value must account for the alpha value which is represented by the first 2 digits. So any hex value fewer than 8 digits will assume a prepended 00 to the hex value and result in a transparent color. DefaultBackgroundColor
will return the result of this environment variable even if it has not been set directly. This environment variable can only set the DefaultBackgroundColor
once. Subsequent updates to background color must be done by setting the property.
IsVisible
Determines whether to show or hide the WebView.
public bool IsVisible { get; set; }
Property Value
Remarks
If IsVisible
is set to false
, the WebView is transparent and is not rendered. However, this does not affect the window containing the WebView (the ParentWindow
parameter that was passed to CreateCoreWebView2ControllerAsync(nint) or CreateCoreWebView2ControllerAsync(nint, CoreWebView2ControllerOptions)).
If you want that window to disappear too, run the corresponding Hide
method from the UI framework on it directly in addition to modifying this.
WebView as a child window does not get window messages when the top window is minimized or restored. For performance reasons, developers should set the IsVisible
property of the WebView to false
when the app window is minimized and back to true
when the app window is restored. The app window does this by handling SIZE_MINIMIZED
and SIZE_RESTORED
command upon receiving WM_SIZE
message. There are CPU and memory benefits when the page is hidden. For instance Chromium has code that throttles activities on the page like animations and some tasks are run less frequently. Similarly, WebView2 will purge some caches to reduce memory usage.
- See Also
-
System.Windows.Forms.Control.Hide
ParentWindow
Gets the parent window provided by the app or sets the parent window that this WebView is using to render content.
public nint ParentWindow { get; set; }
Property Value
Remarks
It initially returns the ParentWindow
passed into CreateCoreWebView2ControllerAsync(nint) or CreateCoreWebView2ControllerAsync(nint, CoreWebView2ControllerOptions). Setting the property causes the WebView to re-parent the main WebView window to the newly provided window.
RasterizationScale
Gets or sets the WebView rasterization scale.
public double RasterizationScale { get; set; }
Property Value
Remarks
The rasterization scale is the combination of the monitor DPI scale and text scaling set by the user. This value should be updated when the DPI scale of the app's top level window changes (i.e. monitor DPI scale changes or the window changes monitor) or when the text scale factor of the system changes. Rasterization scale applies to the WebView content, as well as popups, context menus, scroll bars, and so on. Normal app scaling scenarios should use the ZoomFactor property or SetBoundsAndZoomFactor(Rectangle, double) method.
ShouldDetectMonitorScaleChanges
Determines whether the WebView will detect monitor scale changes.
public bool ShouldDetectMonitorScaleChanges { get; set; }
Property Value
Remarks
ShouldDetectMonitorScaleChanges property determines whether the WebView attempts to track monitor DPI scale changes. When true, the WebView will track monitor DPI scale changes, update the RasterizationScale property, and fire RasterizationScaleChanged event. When false
, the WebView will not track monitor DPI scale changes, and the app must update the RasterizationScale property itself. RasterizationScaleChanged event will never raise when ShouldDetectMonitorScaleChanges is false. Apps that want to set their own rasterization scale should set this property to false to avoid the WebView2 updating the RasterizationScale property to match the monitor DPI scale.
ZoomFactor
Gets or sets the zoom factor for the WebView.
public double ZoomFactor { get; set; }
Property Value
Remarks
Note that changing zoom factor may cause window.innerWidth
or window.innerHeight
and page layout to change. A zoom factor that is applied by the host by setting this ZoomFactor property becomes the new default zoom for the WebView. This zoom factor applies across navigations and is the zoom factor WebView is returned to when the user presses Ctrl+0. When the zoom factor is changed by the user (resulting in the app receiving ZoomFactorChanged), that zoom applies only for the current page. Any user applied zoom is only for the current page and is reset on a navigation. Specifying a ZoomFactor less than or equal to 0 is not allowed. WebView also has an internal supported zoom factor range. When a specified zoom factor is out of that range, it is normalized to be within the range, and a ZoomFactorChanged event is raised for the real applied zoom factor. When this range normalization happens, this reports the zoom factor specified during the previous modification of the ZoomFactor property until the ZoomFactorChanged event is received after WebView applies the normalized zoom factor.
Methods
Close()
Closes the WebView and cleans up the underlying browser instance.
public void Close()
Remarks
Cleaning up the browser instance releases the resources powering the WebView. The browser instance is shut down if no other WebViews are using it.
After running Close, all methods fail and event handlers stop running. Specifically, the WebView releases the associated references to any associated event handlers when Close is run.
Close is implicitly run when the CoreWebView2Controller loses the final reference and is destructed. But it is best practice to explicitly run Close to avoid any accidental cycle of references between the WebView and the app code. Specifically, if you capture a reference to the WebView in an event handler you create a reference cycle between the WebView and the event handler. Run Close to break the cycle by releasing all event handlers. But to avoid the situation, it is best to both explicitly run Close on the WebView and to not capture a reference to the WebView to ensure the WebView is cleaned up correctly. Close is synchronous and won't trigger the beforeunload
event.
MoveFocus(CoreWebView2MoveFocusReason)
Moves focus into WebView.
public void MoveFocus(CoreWebView2MoveFocusReason reason)
Parameters
reason
CoreWebView2MoveFocusReasonThe reason for moving focus.
Remarks
WebView will get focus and focus will be set to correspondent element in the page hosted in the WebView. For Programmatic reason, focus is set to previously focused element or the default element if no previously focused element exists. For Next reason, focus is set to the first element. For Previous reason, focus is set to the last element. WebView changes focus through user interaction including selecting into a WebView or Tab into it. For tabbing, the app runs MoveFocus with Next or Previous to align with Tab and Shift+Tab respectively when it decides the WebView is the next tabbable element.
NotifyParentWindowPositionChanged()
Tells WebView that the main WebView parent (or any ancestor) HWND moved.
public void NotifyParentWindowPositionChanged()
Remarks
This is a notification separate from Bounds. This is needed for accessibility and certain dialogs in WebView to work correctly.
SetBoundsAndZoomFactor(Rectangle, double)
Updates Bounds and ZoomFactor properties at the same time.
public void SetBoundsAndZoomFactor(Rectangle Bounds, double ZoomFactor)
Parameters
Remarks
This operation is atomic from the perspective of the host. After returning from this function, the Bounds and ZoomFactor properties are both updated if the function is successful, or neither is updated if the function fails. If Bounds and ZoomFactor are both updated by the same scale (for example, Bounds and ZoomFactor are both doubled), then the page does not display a change in window.innerWidth
or window.innerHeight
and the WebView renders the content at the new size and zoom without intermediate renderings. This function also updates just one of ZoomFactor or Bounds by passing in the new value for one and the current value for the other.
Events
AcceleratorKeyPressed
AcceleratorKeyPressed is raised when an accelerator key or key combo is pressed or released while the WebView is focused.
public event EventHandler<CoreWebView2AcceleratorKeyPressedEventArgs> AcceleratorKeyPressed
Event Type
Remarks
A key is considered an accelerator if either of the following conditions are true:
- Ctrl or Alt is currently being held.
- The pressed key does not map to a character.
A few specific keys are never considered accelerators, such as Shift. The Escape key is always considered an accelerator.
Autorepeated key events caused by holding the key down will also raise this event. Filter out the auto-repeated key events by verifying KeyEventLParam or PhysicalKeyStatus.
In windowed mode, this event is synchronous. Until you set Handled to true
or the event handler returns, the browser process is blocked and outgoing cross-process COM calls will fail with RPC_E_CANTCALLOUT_ININPUTSYNCCALL. All CoreWebView2 methods work, however.
In windowless mode, the event is asynchronous. Further input do not reach the browser until the event handler returns or Handled is set to true
, but the browser process is not blocked, and outgoing COM calls work normally.
It is recommended to set Handled to true
as early as you are able to know that you want to handle the accelerator key.
GotFocus
GotFocus is raised when WebView gets focus.
public event EventHandler<object> GotFocus
Event Type
LostFocus
LostFocus is raised when WebView loses focus.
public event EventHandler<object> LostFocus
Event Type
Remarks
In the case where MoveFocusRequested event is raised, the focus is still on WebView when MoveFocusRequested event is raised. LostFocus is only raised afterwards when code of the app or default action of MoveFocusRequested event sets focus away from WebView.
MoveFocusRequested
MoveFocusRequested is raised when user tries to tab out of the WebView.
public event EventHandler<CoreWebView2MoveFocusRequestedEventArgs> MoveFocusRequested
Event Type
Remarks
The focus of the WebView has not changed when this event is raised.
RasterizationScaleChanged
RasterizationScaleChanged is raised when the RasterizationScale property changes.
public event EventHandler<object> RasterizationScaleChanged
Event Type
Remarks
The event is raised when the Webview detects that the monitor DPI scale has changed, ShouldDetectMonitorScaleChanges is true, and the Webview has changed the RasterizationScale property.
- See Also
ZoomFactorChanged
ZoomFactorChanged is raised when the ZoomFactor property changes.
public event EventHandler<object> ZoomFactorChanged
Event Type
Remarks
The event may be raised because the ZoomFactor property was modified, or due to the user manually modifying the zoom. When it is modified using the ZoomFactor property, the internal zoom factor is updated immediately and no ZoomFactorChanged event is raised. WebView associates the last used zoom factor for each site. It is possible for the zoom factor to change when navigating to a different page. When the zoom factor changes due to a navigation change, the ZoomFactorChanged event is raised right after the ContentLoading event.
- See Also