首先重写一下 LifeSpanHandler 这个类,我们建立一个新的类 名字叫做 CefLifeSpanHandler 代码如下:
- public class CefLifeSpanHandler : ILifeSpanHandler
- {
- public CefLifeSpanHandler()
- {
-
- }
-
- public bool DoClose(IWebBrowser browserControl, IBrowser browser)
- {
- if (browser.IsDisposed || browser.IsPopup)
- {
- return false;
- }
-
- return true;
- }
-
- public void OnAfterCreated(IWebBrowser browserControl, IBrowser browser)
- {
-
- }
-
- 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;
- var chromiumWebBrowser = (ChromiumWebBrowser)browserControl;
- chromiumWebBrowser.Load(targetUrl);
- return true;
- }
- }
然后我们在实例化 ChromiumWebBrowser 时同时重新赋值 LifeSpanHandler ,代码如下:
- var settings = new CefSettings();
- settings.IgnoreCertificateErrors = true;
- Cef.EnableHighDPISupport();
- Cef.Initialize(settings);
-
- ChromiumWebBrowser Chrome = new ChromiumWebBrowser(url);
-
- // 在这里重新赋值,重写了 LifeSpanHandler ,阻止打开新的窗口
- Chrome.LifeSpanHandler = new CefLifeSpanHandler();
-
- Chrome.BrowserSettings = new BrowserSettings()
- {
- WebGl = CefState.Enabled,
- ImageLoading = CefState.Enabled,
- RemoteFonts = CefState.Enabled,
- AcceptLanguageList = "zh-CN"
- };
-
- // 剩下的省略...
好了代码就到这里了,其它花里胡哨的可以自己去搜索和摸索也可以完全重写 ChromiumWebBrowser , ChromiumWebBrowser 的功能还很强大,这里就需要大家自己研究了,欢迎探讨和分享!