Skip to content

Instantly share code, notes, and snippets.

@vwmberry95
Created April 10, 2018 21:49
Show Gist options
  • Save vwmberry95/a2c1e04e444b8e78ac24b483c63c8d39 to your computer and use it in GitHub Desktop.
Save vwmberry95/a2c1e04e444b8e78ac24b483c63c8d39 to your computer and use it in GitHub Desktop.
using System;
using System.Windows.Forms;
using CefSharp;
using CefSharp.WinForms;
namespace WindowsFormsApp1
{
public class LifeSpanHandler : ILifeSpanHandler
{
private Form1 _form;
public LifeSpanHandler(Form1 form)
{
_form = form;
}
public bool DoClose(IWebBrowser browserControl, IBrowser browser)
{
if (browser.IsPopup)
{
// Get the browser handle
var browserHandle = browser.GetHost().GetWindowHandle();
// Get the host control
var parent = Control.FromChildHandle(browserHandle);
// Get the parent tab
if (parent.Parent is TabPage tab)
{
// Close the tab
_form.CloseTab(tab);
}
}
return true;
}
public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
{
if (browser.IsPopup)
{
// Get the browser handle
var browserHandle = browser.GetHost().GetWindowHandle();
// Get the host control
var parent = Control.FromChildHandle(browserHandle);
// Get the parent tab
if (parent.Parent is TabPage tab)
{
// Set the browser
tab.Tag = browserControl;
}
}
}
public void OnBeforeClose(IWebBrowser browserControl, IBrowser browser)
{
}
public bool OnBeforePopup(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, string targetFrameName, WindowOpenDisposition targetDisposition, bool userGesture, IPopupFeatures popupFeatures, IWindowInfo windowInfo, IBrowserSettings browserSettings, ref bool noJavascriptAccess, out IWebBrowser newBrowser)
{
newBrowser = null;
(browserControl as ChromiumWebBrowser).Invoke(new Action(() =>
{
// Create a new browser tab
var control = _form.AddNewPopup(targetUrl);
var rect = control.ClientRectangle;
// Set the new window as a child of the new browser tab
windowInfo.SetAsChild(control.Handle, rect.Left, rect.Top, rect.Right, rect.Bottom);
}));
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment