From 6793ff2355fbc6672b868675b3336ef5bc5a4cd2 Mon Sep 17 00:00:00 2001 From: amaitland Date: Mon, 9 Dec 2019 20:04:46 +1000 Subject: [PATCH] Core - Add WinFormsWebBrowserExtensions.DestroyWindow helper function Used to manually destroy a browser instance (can be used to avoid having CEF send a WM_Close message). MUST BE CALLED ON THE CEF UI Thread, see xml doc example --- .../WinFormsWebBrowserExtensions.cs | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 CefSharp.WinForms/WinFormsWebBrowserExtensions.cs diff --git a/CefSharp.WinForms/WinFormsWebBrowserExtensions.cs b/CefSharp.WinForms/WinFormsWebBrowserExtensions.cs new file mode 100644 index 000000000..2b69b241a --- /dev/null +++ b/CefSharp.WinForms/WinFormsWebBrowserExtensions.cs @@ -0,0 +1,61 @@ +// Copyright © 2019 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; + +namespace CefSharp.WinForms +{ + /// + /// Helper extensions for performing common CefSharp related WinForms tasks + /// + public static class WinFormsWebBrowserExtensions + { + [System.Runtime.InteropServices.DllImport("user32.dll")] + private static extern bool DestroyWindow(IntPtr hWnd); + + /// + /// Manually call https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-destroywindow + /// passing in the handle returned from . + /// This method can be used to manually close the underlying CefBrowser instance. + /// This will avoid the WM_Close message that CEF sends by default to the top level window. + /// (Which closes your application). This method should generally only be used in the WinForms version. + /// + /// the ChromiumWebBrowser instance + /// If the function succeeds, the return value is true. + /// + /// + /// //Invoke on the CEF UI Thread + /// Cef.UIThreadTaskFactory.StartNew(() => + /// { + /// var closed = chromiumWebBrowser.DestroyWindow(); + /// }); + /// + /// + public static bool DestroyWindow(this IWebBrowser chromiumWebBrowser) + { + if (!Cef.CurrentlyOnThread(CefThreadIds.TID_UI)) + { + throw new InvalidOperationException("This method can only be called on the CEF UI thread." + + "Use Cef.UIThreadTaskFactory to marshal your call onto the CEF UI Thread."); + } + + if (chromiumWebBrowser.IsDisposed) + { + return false; + } + + var browser = chromiumWebBrowser.GetBrowser(); + + if (browser == null) + { + return false; + } + + var handle = browser.GetHost().GetWindowHandle(); + + + return DestroyWindow(handle); + } + } +}