Skip to content

Instantly share code, notes, and snippets.

@amaitland
Last active August 26, 2019 01:46
Show Gist options
  • Save amaitland/0aa9532aa861701e9869dd1a4b46d233 to your computer and use it in GitHub Desktop.
Save amaitland/0aa9532aa861701e9869dd1a4b46d233 to your computer and use it in GitHub Desktop.
WPF ChromiumWebBrowser Load before attaching to visual tree
using CefSharp.Wpf;
using System;
namespace CefSharp.MinimalExample.Wpf
{
/// <summary>
/// ChromiumWebBrowser that loads before being attached to the visual tree
/// </summary>
/// <example>
/// <code>
/// //Obtain Hwnd from parent window
/// var hwndSource = (HwndSource)PresentationSource.FromVisual(this);
/// var browser = new CustomChromiumWebBrowser(hwndSource.Handle, "github.com", 1024, 768);
/// </code>
/// </example>
public class CustomChromiumWebBrowser : ChromiumWebBrowser
{
private readonly IntPtr parentWindowHandle;
public CustomChromiumWebBrowser(IntPtr parentWindowHandle, string address, int width, int height) : base(address)
{
this.parentWindowHandle = parentWindowHandle;
CreateOffscreenBrowser(new System.Windows.Size(width, height));
Loaded += OnCustomChromiumWebBrowserLoaded;
}
private void OnCustomChromiumWebBrowserLoaded(object sender, System.Windows.RoutedEventArgs e)
{
Loaded -= OnCustomChromiumWebBrowserLoaded;
//If the browser has finished rendering before we attach to the Visual Tree
//then ask for a new frame to be generated
var host = this.GetBrowserHost();
if (host != null)
{
host.Invalidate(PaintElementType.View);
}
}
protected override IWindowInfo CreateOffscreenBrowserWindowInfo(IntPtr handle)
{
//If we aren't attached to the Visual Tree when the browser is created
//Then we should use the parentWindowHandle(HWND) passed in to the constructor
return base.CreateOffscreenBrowserWindowInfo(handle == IntPtr.Zero ? parentWindowHandle : handle);
}
}
}
using System.Windows;
using System.Windows.Interop;
namespace CefSharp.MinimalExample.Wpf
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += OnMainWindowLoaded;
}
private void OnMainWindowLoaded(object sender, RoutedEventArgs e)
{
var hwndSource = (HwndSource)PresentationSource.FromVisual(this);
var browser = new CustomChromiumWebBrowser(hwndSource.Handle, "github.com", 1024, 768);
browser.LoadingStateChanged += OnBrowserLoadingStateChanged;
}
private void OnBrowserLoadingStateChanged(object sender, LoadingStateChangedEventArgs e)
{
if (e.IsLoading == false)
{
var browser = (CustomChromiumWebBrowser)sender;
browser.LoadingStateChanged -= OnBrowserLoadingStateChanged;
Dispatcher.InvokeAsync(() =>
{
//Attach to visual tree
BrowserBorder.Child = browser;
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment