// Copyright © 2013 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System; using System.ComponentModel; using System.Drawing; using System.Runtime.CompilerServices; using System.Threading; using System.Windows.Forms; using CefSharp.Internals; using CefSharp.WinForms.Internals; namespace CefSharp.WinForms { /// /// ChromiumWebBrowser is the WinForms web browser control /// /// /// /// [Docking(DockingBehavior.AutoDock), DefaultEvent("LoadingStateChanged"), ToolboxBitmap(typeof(ChromiumWebBrowser)), Description("CefSharp ChromiumWebBrowser - Chromium Embedded Framework .Net wrapper. https://github.com/cefsharp/CefSharp"), Designer(typeof(ChromiumWebBrowserDesigner))] public class ChromiumWebBrowser : Control, IWebBrowserInternal, IWinFormsWebBrowser { /// /// The managed cef browser adapter /// private ManagedCefBrowserAdapter managedCefBrowserAdapter; /// /// The parent form message interceptor /// private ParentFormMessageInterceptor parentFormMessageInterceptor; /// /// The browser /// private IBrowser browser; /// /// A flag that indicates whether or not the designer is active /// NOTE: DesignMode becomes false by the time we get to the destructor/dispose so it gets stored here /// private bool designMode; /// /// A flag that indicates whether or not has been called. /// private bool initialized; /// /// Has the underlying Cef Browser been created (slightly different to initliazed in that /// the browser is initialized in an async fashion) /// private bool browserCreated; /// /// Browser initialization settings /// private IBrowserSettings browserSettings; /// /// The request context (we deliberately use a private variable so we can throw an exception if /// user attempts to set after browser created) /// private IRequestContext requestContext; /// /// The value for disposal, if it's 1 (one) then this instance is either disposed /// or in the process of getting disposed /// private int disposeSignaled; /// /// Gets a value indicating whether this instance is disposed. /// /// if this instance is disposed; otherwise, . [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(false)] public new bool IsDisposed { get { return Interlocked.CompareExchange(ref disposeSignaled, 1, 1) == 1; } } /// /// Set to true while handing an activating WM_ACTIVATE message. /// MUST ONLY be cleared by DefaultFocusHandler. /// /// true if this instance is activating; otherwise, false. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(false)] public bool IsActivating { get; set; } /// /// Gets or sets the browser settings. /// /// The browser settings. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IBrowserSettings BrowserSettings { get { return browserSettings; } set { if (browserCreated) { throw new Exception("Browser has already been created. BrowserSettings must be " + "set before the underlying CEF browser is created."); } if (value != null && value.GetType() != typeof(BrowserSettings)) { throw new Exception(string.Format("BrowserSettings can only be of type {0} or null", typeof(BrowserSettings))); } browserSettings = value; } } /// /// Activates browser upon creation, the default value is false. Prior to version 73 /// the default behaviour was to activate browser on creation (Equivilent of setting this property to true). /// To restore this behaviour set this value to true immediately after you create the instance. /// https://bitbucket.org/chromiumembedded/cef/issues/1856/branch-2526-cef-activates-browser-window /// public bool ActivateBrowserOnCreation { get; set; } /// /// Gets or sets the request context. /// /// The request context. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IRequestContext RequestContext { get { return requestContext; } set { if (browserCreated) { throw new Exception("Browser has already been created. RequestContext must be " + "set before the underlying CEF browser is created."); } if (value != null && value.GetType() != typeof(RequestContext)) { throw new Exception(string.Format("RequestContxt can only be of type {0} or null", typeof(RequestContext))); } requestContext = value; } } /// /// A flag that indicates whether the control is currently loading one or more web pages (true) or not (false). /// /// true if this instance is loading; otherwise, false. /// In the WPF control, this property is implemented as a Dependency Property and fully supports data /// binding. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(false)] public bool IsLoading { get; private set; } /// /// The text that will be displayed as a ToolTip /// /// The tooltip text. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public string TooltipText { get; private set; } /// /// The address (URL) which the browser control is currently displaying. /// Will automatically be updated as the user navigates to another page (e.g. by clicking on a link). /// /// The address. /// In the WPF control, this property is implemented as a Dependency Property and fully supports data /// binding. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public string Address { get; private set; } /// /// Implement and assign to handle dialog events. /// /// The dialog handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IDialogHandler DialogHandler { get; set; } /// /// Implement and assign to handle events related to JavaScript Dialogs. /// /// The js dialog handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IJsDialogHandler JsDialogHandler { get; set; } /// /// Implement and assign to handle events related to key press. /// /// The keyboard handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IKeyboardHandler KeyboardHandler { get; set; } /// /// Implement and assign to handle events related to browser requests. /// /// The request handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IRequestHandler RequestHandler { get; set; } /// /// Implement and assign to handle events related to downloading files. /// /// The download handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IDownloadHandler DownloadHandler { get; set; } /// /// Implement and assign to handle events related to browser load status. /// /// The load handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public ILoadHandler LoadHandler { get; set; } /// /// Implement and assign to handle events related to popups. /// /// The life span handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public ILifeSpanHandler LifeSpanHandler { get; set; } /// /// Implement and assign to handle events related to browser display state. /// /// The display handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IDisplayHandler DisplayHandler { get; set; } /// /// Implement and assign to handle events related to the browser context menu /// /// The menu handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IContextMenuHandler MenuHandler { get; set; } /// /// Implement and assign to handle messages from the render process. /// /// The render process message handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IRenderProcessMessageHandler RenderProcessMessageHandler { get; set; } /// /// Implement to handle events related to find results. /// /// The find handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IFindHandler FindHandler { get; set; } /// /// Implement to handle audio events. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IAudioHandler AudioHandler { get; set; } /// /// The for this ChromiumWebBrowser. /// /// The focus handler. /// If you need customized focus handling behavior for WinForms, the suggested /// best practice would be to inherit from DefaultFocusHandler and try to avoid /// needing to override the logic in OnGotFocus. The implementation in /// DefaultFocusHandler relies on very detailed behavior of how WinForms and /// Windows interact during window activation. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IFocusHandler FocusHandler { get; set; } /// /// Implement and assign to handle events related to dragging. /// /// The drag handler. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IDragHandler DragHandler { get; set; } /// /// Implement and control the loading of resources /// /// The resource handler factory. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(null)] public IResourceRequestHandlerFactory ResourceRequestHandlerFactory { get; set; } /// /// Event handler that will get called when the resource load for a navigation fails or is canceled. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// public event EventHandler LoadError; /// /// Event handler that will get called when the browser begins loading a frame. Multiple frames may be loading at the same /// time. Sub-frames may start or continue loading after the main frame load has ended. This method may not be called for a /// particular frame if the load request for that frame fails. For notification of overall browser load status use /// OnLoadingStateChange instead. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// /// Whilst this may seem like a logical place to execute js, it's called before the DOM has been loaded, implement /// as it's called when the underlying V8Context is created /// public event EventHandler FrameLoadStart; /// /// Event handler that will get called when the browser is done loading a frame. Multiple frames may be loading at the same /// time. Sub-frames may start or continue loading after the main frame load has ended. This method will always be called /// for all frames irrespective of whether the request completes successfully. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// public event EventHandler FrameLoadEnd; /// /// Event handler that will get called when the Loading state has changed. /// This event will be fired twice. Once when loading is initiated either programmatically or /// by user action, and once when loading is terminated due to completion, cancellation of failure. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// public event EventHandler LoadingStateChanged; /// /// Event handler for receiving Javascript console messages being sent from web pages. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// (The exception to this is when your running with settings.MultiThreadedMessageLoop = false, then they'll be the same thread). /// public event EventHandler ConsoleMessage; /// /// Event handler for changes to the status message. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// (The exception to this is when your running with settings.MultiThreadedMessageLoop = false, then they'll be the same thread). /// public event EventHandler StatusMessage; /// /// Occurs when the browser address changed. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// public event EventHandler AddressChanged; /// /// Occurs when the browser title changed. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// public event EventHandler TitleChanged; /// /// Event called after the underlying CEF browser instance has been created. /// It's important to note this event is fired on a CEF UI thread, which by default is not the same as your application UI /// thread. It is unwise to block on this thread for any length of time as your browser will become unresponsive and/or hang.. /// To access UI elements you'll need to Invoke/Dispatch onto the UI Thread. /// public event EventHandler IsBrowserInitializedChanged; /// /// Event handler that will get called when the message that originates from CefSharp.PostMessage /// public event EventHandler JavascriptMessageReceived; /// /// A flag that indicates whether the state of the control currently supports the GoForward action (true) or not (false). /// /// true if this instance can go forward; otherwise, false. /// In the WPF control, this property is implemented as a Dependency Property and fully supports data /// binding. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(false)] public bool CanGoForward { get; private set; } /// /// A flag that indicates whether the state of the control current supports the GoBack action (true) or not (false). /// /// true if this instance can go back; otherwise, false. /// In the WPF control, this property is implemented as a Dependency Property and fully supports data /// binding. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(false)] public bool CanGoBack { get; private set; } /// /// A flag that indicates whether the WebBrowser is initialized (true) or not (false). /// /// true if this instance is browser initialized; otherwise, false. /// In the WPF control, this property is implemented as a Dependency Property and fully supports data /// binding. [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(false)] public bool IsBrowserInitialized { get; private set; } /// /// A flag that indicates if you can execute javascript in the main frame. /// Flag is set to true in IRenderProcessMessageHandler.OnContextCreated. /// and false in IRenderProcessMessageHandler.OnContextReleased /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(false)] public bool CanExecuteJavascriptInMainFrame { get; private set; } /// /// ParentFormMessageInterceptor hooks the Form handle and forwards /// the move/active messages to the browser, the default is true /// and should only be required when using /// set to true. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), DefaultValue(true)] public bool UseParentFormMessageInterceptor { get; set; } = true; /// /// Initializes static members of the class. /// static ChromiumWebBrowser() { if (CefSharpSettings.ShutdownOnExit) { Application.ApplicationExit += OnApplicationExit; } } /// /// Handles the event. /// /// The sender. /// The instance containing the event data. private static void OnApplicationExit(object sender, EventArgs e) { Cef.Shutdown(); } /// /// This constructor exists as the WinForms designer requires a parameterless constructor, if you are instantiating /// an instance of this class in code then use the /// constructor overload instead. Using this constructor in code is unsupported and you may experience 's /// when attempting to access some of the properties immediately after instantiation. /// [Obsolete("Should only be used by the WinForms Designer. Use the ChromiumWebBrowser(string, IRequestContext) constructor overload instead.")] public ChromiumWebBrowser() { } /// /// Initializes a new instance of the class. /// /// The address. /// Request context that will be used for this browser instance, /// if null the Global Request Context will be used public ChromiumWebBrowser(string address, IRequestContext requestContext = null) { Dock = DockStyle.Fill; Address = address; RequestContext = requestContext; InitializeFieldsAndCefIfRequired(); } /// /// Required for designer support - this method cannot be inlined as the designer /// will attempt to load libcef.dll and will subsiquently throw an exception. /// TODO: Still not happy with this method name, need something better /// [MethodImpl(MethodImplOptions.NoInlining)] private void InitializeFieldsAndCefIfRequired() { if (!initialized) { if (!Cef.IsInitialized && !Cef.Initialize(new CefSettings())) { throw new InvalidOperationException("Cef::Initialize() failed"); } Cef.AddDisposable(this); if (FocusHandler == null) { FocusHandler = new DefaultFocusHandler(); } if (browserSettings == null) { browserSettings = new BrowserSettings(frameworkCreated: true); } managedCefBrowserAdapter = new ManagedCefBrowserAdapter(this, false); initialized = true; } } /// /// If not in design mode; Releases unmanaged and - optionally - managed resources for the /// /// to release both managed and unmanaged resources; to release only unmanaged resources. protected override void Dispose(bool disposing) { // Attempt to move the disposeSignaled state from 0 to 1. If successful, we can be assured that // this thread is the first thread to do so, and can safely dispose of the object. if (Interlocked.CompareExchange(ref disposeSignaled, 1, 0) != 0) { return; } if (!designMode) { InternalDispose(disposing); } base.Dispose(disposing); } /// /// Releases unmanaged and - optionally - managed resources for the /// /// to release both managed and unmanaged resources; to release only unmanaged resources. /// /// This method cannot be inlined as the designer will attempt to load libcef.dll and will subsiquently throw an exception. /// [MethodImpl(MethodImplOptions.NoInlining)] private void InternalDispose(bool disposing) { if (disposing) { IsBrowserInitialized = false; // Don't maintain a reference to event listeners anylonger: AddressChanged = null; ConsoleMessage = null; FrameLoadEnd = null; FrameLoadStart = null; IsBrowserInitializedChanged = null; LoadError = null; LoadingStateChanged = null; StatusMessage = null; TitleChanged = null; JavascriptMessageReceived = null; // Release reference to handlers, except LifeSpanHandler which is done after Disposing // ManagedCefBrowserAdapter otherwise the ILifeSpanHandler.DoClose will not be invoked. this.SetHandlersToNullExceptLifeSpan(); browser = null; if (parentFormMessageInterceptor != null) { parentFormMessageInterceptor.Dispose(); parentFormMessageInterceptor = null; } if (managedCefBrowserAdapter != null) { managedCefBrowserAdapter.Dispose(); managedCefBrowserAdapter = null; } // LifeSpanHandler is set to null after managedCefBrowserAdapter.Dispose so ILifeSpanHandler.DoClose // is called. LifeSpanHandler = null; } Cef.RemoveDisposable(this); } /// /// Loads the specified URL. /// /// The URL to be loaded. public void Load(string url) { if (IsBrowserInitialized) { using (var frame = this.GetMainFrame()) { frame.LoadUrl(url); } } else { Address = url; } } /// /// The javascript object repository, one repository per ChromiumWebBrowser instance. /// [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IJavascriptObjectRepository JavascriptObjectRepository { get { InitializeFieldsAndCefIfRequired(); return managedCefBrowserAdapter == null ? null : managedCefBrowserAdapter.JavascriptObjectRepository; } } /// /// Raises the event. /// /// An that contains the event data. protected override void OnHandleCreated(EventArgs e) { designMode = DesignMode; if (!designMode) { InitializeFieldsAndCefIfRequired(); // NOTE: Had to move the code out of this function otherwise the designer would crash CreateBrowser(); ResizeBrowser(); } base.OnHandleCreated(e); } /// /// Override this method to handle creation of WindowInfo. This method can be used to customise aspects of /// browser creation including configuration of settings such as . /// Window Activation is disabled by default, you can re-enable it by overriding and removing the /// WS_EX_NOACTIVATE style from . /// /// Window handle for the Control /// Window Info /// /// To re-enable Window Activation then remove WS_EX_NOACTIVATE from ExStyle /// /// const uint WS_EX_NOACTIVATE = 0x08000000; /// windowInfo.ExStyle &= ~WS_EX_NOACTIVATE; /// /// protected virtual IWindowInfo CreateBrowserWindowInfo(IntPtr handle) { //TODO: If we start adding more consts then extract them into a common class //Possibly in the CefSharp assembly and move the WPF ones into there as well. const uint WS_EX_NOACTIVATE = 0x08000000; var windowInfo = new WindowInfo(); windowInfo.SetAsChild(handle); if (!ActivateBrowserOnCreation) { //Disable Window activation by default //https://bitbucket.org/chromiumembedded/cef/issues/1856/branch-2526-cef-activates-browser-window windowInfo.ExStyle |= WS_EX_NOACTIVATE; } return windowInfo; } [MethodImpl(MethodImplOptions.NoInlining)] private void CreateBrowser() { browserCreated = true; if (((IWebBrowserInternal)this).HasParent == false) { if (IsBrowserInitialized == false || browser == null) { var windowInfo = CreateBrowserWindowInfo(Handle); managedCefBrowserAdapter.CreateBrowser(windowInfo, browserSettings as BrowserSettings, requestContext as RequestContext, Address); browserSettings = null; } else { //If the browser already exists we'll reparent it to the new Handle var browserHandle = browser.GetHost().GetWindowHandle(); NativeMethodWrapper.SetWindowParent(browserHandle, Handle); } } } /// /// Called after browser created. /// /// The browser. void IWebBrowserInternal.OnAfterBrowserCreated(IBrowser browser) { this.browser = browser; IsBrowserInitialized = true; // By the time this callback gets called, this control // is most likely hooked into a browser Form of some sort. // (Which is what ParentFormMessageInterceptor relies on.) // Ensure the ParentFormMessageInterceptor construction occurs on the WinForms UI thread: if (UseParentFormMessageInterceptor) { this.InvokeOnUiThreadIfRequired(() => { parentFormMessageInterceptor = new ParentFormMessageInterceptor(this); }); } ResizeBrowser(); IsBrowserInitializedChanged?.Invoke(this, EventArgs.Empty); } /// /// Sets the address. /// /// The instance containing the event data. void IWebBrowserInternal.SetAddress(AddressChangedEventArgs args) { Address = args.Address; var handler = AddressChanged; if (handler != null) { handler(this, args); } } /// /// Sets the loading state change. /// /// The instance containing the event data. void IWebBrowserInternal.SetLoadingStateChange(LoadingStateChangedEventArgs args) { CanGoBack = args.CanGoBack; CanGoForward = args.CanGoForward; IsLoading = args.IsLoading; var handler = LoadingStateChanged; if (handler != null) { handler(this, args); } } /// /// Sets the title. /// /// The instance containing the event data. void IWebBrowserInternal.SetTitle(TitleChangedEventArgs args) { var handler = TitleChanged; if (handler != null) { handler(this, args); } } /// /// Sets the tooltip text. /// /// The tooltip text. void IWebBrowserInternal.SetTooltipText(string tooltipText) { TooltipText = tooltipText; } /// /// Handles the event. /// /// The instance containing the event data. void IWebBrowserInternal.OnFrameLoadStart(FrameLoadStartEventArgs args) { var handler = FrameLoadStart; if (handler != null) { handler(this, args); } } /// /// Handles the event. /// /// The instance containing the event data. void IWebBrowserInternal.OnFrameLoadEnd(FrameLoadEndEventArgs args) { var handler = FrameLoadEnd; if (handler != null) { handler(this, args); } } /// /// Handles the event. /// /// The instance containing the event data. void IWebBrowserInternal.OnConsoleMessage(ConsoleMessageEventArgs args) { var handler = ConsoleMessage; if (handler != null) { handler(this, args); } } /// /// Handles the event. /// /// The instance containing the event data. void IWebBrowserInternal.OnStatusMessage(StatusMessageEventArgs args) { var handler = StatusMessage; if (handler != null) { handler(this, args); } } /// /// Handles the event. /// /// The instance containing the event data. void IWebBrowserInternal.OnLoadError(LoadErrorEventArgs args) { var handler = LoadError; if (handler != null) { handler(this, args); } } void IWebBrowserInternal.SetCanExecuteJavascriptOnMainFrame(bool canExecute) { CanExecuteJavascriptInMainFrame = canExecute; } void IWebBrowserInternal.SetJavascriptMessageReceived(JavascriptMessageReceivedEventArgs args) { JavascriptMessageReceived?.Invoke(this, args); } /// /// Gets the browser adapter. /// /// The browser adapter. IBrowserAdapter IWebBrowserInternal.BrowserAdapter { get { return managedCefBrowserAdapter; } } /// /// Gets or sets a value indicating whether this instance has parent. /// /// true if this instance has parent; otherwise, false. bool IWebBrowserInternal.HasParent { get; set; } /// /// Manually implement Focused because cef does not implement it. /// /// true if focused; otherwise, false. /// This is also how the Microsoft's WebBrowserControl implements the Focused property. public override bool Focused { get { if (base.Focused) { return true; } if (!IsHandleCreated) { return false; } return NativeMethodWrapper.IsFocused(Handle); } } /// /// Raises the event. /// /// An that contains the event data. protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); if (!designMode && initialized) { ResizeBrowser(); } } /// /// Resizes the browser. /// private void ResizeBrowser() { if (IsBrowserInitialized) { managedCefBrowserAdapter.Resize(Width, Height); } } /// /// Raises the event. /// /// An that contains the event data. protected override void OnGotFocus(EventArgs e) { if (IsBrowserInitialized) { browser.GetHost().SetFocus(true); } base.OnGotFocus(e); } /// /// Returns the current IBrowser Instance /// /// browser instance or null public IBrowser GetBrowser() { this.ThrowExceptionIfBrowserNotInitialized(); return browser; } /// /// Makes certain keys as Input keys when CefSettings.MultiThreadedMessageLoop = false /// /// key data /// true for a select list of keys otherwise defers to base.IsInputKey protected override bool IsInputKey(Keys keyData) { //This code block is only called/required when CEF is running in the //same message loop as the WinForms UI (CefSettings.MultiThreadedMessageLoop = false) //Without this code, arrows and tab won't be processed switch (keyData) { case Keys.Right: case Keys.Left: case Keys.Up: case Keys.Down: case Keys.Tab: { return true; } case Keys.Shift | Keys.Right: case Keys.Shift | Keys.Left: case Keys.Shift | Keys.Up: case Keys.Shift | Keys.Down: { return true; } } return base.IsInputKey(keyData); } } }