WinForms - Add ChromiumRenderWidgetHandleFinder/ChromiumWidgetNativeWindow

Used to hook the low level HWND and get message (e.g. mouse messages)

Updated the example
This commit is contained in:
Alex Maitland
2021-05-11 20:39:14 +10:00
parent f81f2e1119
commit e4c585609e
6 changed files with 173 additions and 114 deletions
@@ -12,6 +12,7 @@ using CefSharp.Example;
using CefSharp.Example.Handlers;
using CefSharp.Example.JavascriptBinding;
using CefSharp.WinForms.Example.Handlers;
using CefSharp.WinForms.Experimental;
namespace CefSharp.WinForms.Example
{
@@ -19,7 +20,7 @@ namespace CefSharp.WinForms.Example
{
public IWinFormsWebBrowser Browser { get; private set; }
private IntPtr browserHandle;
private ChromeWidgetMessageInterceptor messageInterceptor;
private ChromiumWidgetNativeWindow messageInterceptor;
private bool multiThreadedMessageLoopEnabled;
public BrowserTabUserControl(Action<string, int?> openNewTab, string url, bool multiThreadedMessageLoopEnabled)
@@ -277,9 +278,11 @@ namespace CefSharp.WinForms.Example
while (true)
{
IntPtr chromeWidgetHostHandle;
if (ChromeWidgetHandleFinder.TryFindHandle(browserHandle, out chromeWidgetHostHandle))
if (ChromiumRenderWidgetHandleFinder.TryFindHandle(Browser, out chromeWidgetHostHandle))
{
messageInterceptor = new ChromeWidgetMessageInterceptor((Control)Browser, chromeWidgetHostHandle, message =>
messageInterceptor = new ChromiumWidgetNativeWindow((Control)Browser, chromeWidgetHostHandle);
messageInterceptor.OnWndProc(message =>
{
const int WM_MOUSEACTIVATE = 0x0021;
const int WM_NCLBUTTONDOWN = 0x00A1;
@@ -289,7 +292,7 @@ namespace CefSharp.WinForms.Example
if (message.Msg == WM_DESTROY)
{
SetupMessageInterceptor();
return;
return false;
}
if (message.Msg == WM_MOUSEACTIVATE)
@@ -324,6 +327,8 @@ namespace CefSharp.WinForms.Example
// Console.WriteLine("WM_MOUSELEAVE");
// break;
//}
return false;
});
break;
@@ -84,7 +84,6 @@
<Compile Include="BrowserTabUserControl.Designer.cs">
<DependentUpon>BrowserTabUserControl.cs</DependentUpon>
</Compile>
<Compile Include="ChromeWidgetMessageInterceptor.cs" />
<Compile Include="ChromiumContainerControl.cs">
<SubType>Component</SubType>
</Compile>
@@ -1,109 +0,0 @@
// Copyright © 2015 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.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
namespace CefSharp.WinForms.Example
{
/// <summary>
/// Intercepts Windows messages sent to the ChromiumWebBrowser control's widget sub-window.
///
/// It is necessary to listen to the widget sub-window because it receives all Windows messages
/// and forwards them to CEF, rather than the ChromiumWebBrowser.Handle.
///
/// The supplied Action delegate is fired upon each message.
/// </summary>
internal class ChromeWidgetMessageInterceptor : NativeWindow
{
private Action<Message> forwardAction;
internal ChromeWidgetMessageInterceptor(Control browser, IntPtr chromeWidgetHostHandle, Action<Message> forwardAction)
{
AssignHandle(chromeWidgetHostHandle);
browser.HandleDestroyed += BrowserHandleDestroyed;
this.forwardAction = forwardAction;
}
private void BrowserHandleDestroyed(object sender, EventArgs e)
{
ReleaseHandle();
var browser = (Control)sender;
browser.HandleDestroyed -= BrowserHandleDestroyed;
forwardAction = null;
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (forwardAction != null)
{
forwardAction(m);
}
}
}
internal static class ChromeWidgetHandleFinder
{
private delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
private class ClassDetails
{
public IntPtr DescendantFound { get; set; }
}
private static bool EnumWindow(IntPtr hWnd, IntPtr lParam)
{
const string chromeWidgetHostClassName = "Chrome_RenderWidgetHostHWND";
var buffer = new StringBuilder(128);
GetClassName(hWnd, buffer, buffer.Capacity);
if (buffer.ToString() == chromeWidgetHostClassName)
{
var gcHandle = GCHandle.FromIntPtr(lParam);
var classDetails = (ClassDetails)gcHandle.Target;
classDetails.DescendantFound = hWnd;
return false;
}
return true;
}
/// <summary>
/// Chrome's message-loop Window isn't created synchronously, so this may not find it.
/// If so, you need to wait and try again later.
/// </summary>
public static bool TryFindHandle(IntPtr browserHandle, out IntPtr chromeWidgetHostHandle)
{
var classDetails = new ClassDetails();
var gcHandle = GCHandle.Alloc(classDetails);
var childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(browserHandle, childProc, GCHandle.ToIntPtr(gcHandle));
chromeWidgetHostHandle = classDetails.DescendantFound;
gcHandle.Free();
return classDetails.DescendantFound != IntPtr.Zero;
}
}
}
@@ -58,6 +58,8 @@
</Compile>
<Compile Include="CefSettings.cs" />
<Compile Include="ChromiumWebBrowserDesigner.cs" />
<Compile Include="Experimental\ChromiumRenderWidgetHandleFinder.cs" />
<Compile Include="Experimental\ChromiumWidgetNativeWindow.cs" />
<Compile Include="Internals\DefaultFocusHandler.cs" />
<Compile Include="Internals\ControlExtensions.cs" />
<Compile Include="Internals\ParentFormMessageInterceptor.cs" />
@@ -0,0 +1,93 @@
// Copyright © 2015 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.Runtime.InteropServices;
using System.Text;
namespace CefSharp.WinForms.Experimental
{
/// <summary>
/// ChromiumWidgetHandleFinder is a helper class used to find the <see cref="ChromeRenderWidgetHostClassName"/>
/// child Hwnd for the browser instance.
/// </summary>
public static class ChromiumRenderWidgetHandleFinder
{
/// <summary>
/// Class Name of the Chrome_RenderWidgetHostHWND Child Window
/// </summary>
public const string ChromeRenderWidgetHostClassName = "Chrome_RenderWidgetHostHWND";
/// <summary>
/// EnumWindowProc delegate used by <see cref="EnumChildWindows(IntPtr, EnumWindowProc, IntPtr)"/>
/// </summary>
/// <param name="hwnd">A handle to a child window of the parent window specified in EnumChildWindows</param>
/// <param name="lParam">The application-defined value given in EnumChildWindows</param>
/// <returns>To continue enumeration, the callback function must return true; to stop enumeration, it must return false.</returns>
private delegate bool EnumWindowProc(IntPtr hwnd, IntPtr lParam);
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
/// <summary>
/// Chromium's message-loop Window isn't created synchronously, so this may not find it.
/// If so, you need to wait and try again later.
/// </summary>
/// <param name="chromiumWebBrowser">ChromiumWebBrowser instance</param>
/// <param name="chromerRenderWidgetHostHandle">Handle of the child HWND with the name <see cref="ChromeRenderWidgetHostClassName"/></param>
/// <returns>returns true if the HWND was found otherwise false.</returns>
public static bool TryFindHandle(IWebBrowser chromiumWebBrowser, out IntPtr chromerRenderWidgetHostHandle)
{
var host = chromiumWebBrowser.GetBrowserHost();
if (host == null)
{
throw new Exception("IBrowserHost is null, you've likely call this method before the underlying browser has been created.");
}
var hwnd = host.GetWindowHandle();
return TryFindHandle(hwnd, ChromeRenderWidgetHostClassName, out chromerRenderWidgetHostHandle);
}
/// <summary>
/// Helper function used to find the child HWND with the ClassName matching <paramref name="chromeRenderWidgetHostClassName"/>
/// Chromium's message-loop Window isn't created synchronously, so this may not find it.
/// If so, you need to wait and try again later.
/// In most cases you should use the <see cref="TryFindHandle(ChromiumWebBrowser, out IntPtr)"/> overload.
/// </summary>
/// <param name="chromiumWebBrowserHandle"><see cref="ChromiumWebBrowser"/> control Handle</param>
/// <param name="chromeRenderWidgetHostClassName">class name used to match</param>
/// <param name="chromerRenderWidgetHostHandle">Handle of the child HWND with the name <see cref="ChromeRenderWidgetHostClassName"/></param>
/// <returns>returns true if the HWND was found otherwise false.</returns>
public static bool TryFindHandle(IntPtr chromiumWebBrowserHandle, string chromeRenderWidgetHostClassName, out IntPtr chromerRenderWidgetHostHandle)
{
var chromeRenderWidgetHostHwnd = IntPtr.Zero;
EnumWindowProc childProc = (IntPtr hWnd, IntPtr lParam) =>
{
var buffer = new StringBuilder(128);
GetClassName(hWnd, buffer, buffer.Capacity);
if (buffer.ToString() == chromeRenderWidgetHostClassName)
{
chromeRenderWidgetHostHwnd = hWnd;
return false;
}
return true;
};
EnumChildWindows(chromiumWebBrowserHandle, childProc, IntPtr.Zero);
chromerRenderWidgetHostHandle = chromeRenderWidgetHostHwnd;
return chromerRenderWidgetHostHandle != IntPtr.Zero;
}
}
}
@@ -0,0 +1,69 @@
// Copyright © 2015 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.Windows.Forms;
namespace CefSharp.WinForms.Experimental
{
/// <summary>
/// Provides a convenient <see cref="NativeWindow"/> implement
/// that can be used without having to create your own class
/// </summary>
public class ChromiumWidgetNativeWindow : NativeWindow
{
private Func<Message, bool> wndProcHandler;
/// <summary>
/// ChromiumWidgetMessageInterceptor constructor
/// </summary>
/// <param name="control">Control is used to handled the <see cref="Control.HandleDestroyed"/> event so
/// we can automatically call <see cref="NativeWindow.ReleaseHandle"/>. If null then you are responsible
/// for calling <see cref="NativeWindow.ReleaseHandle"/></param>
/// <param name="chromeWidgetHostHandle">Hwnd to intercept messages for.</param>
public ChromiumWidgetNativeWindow(Control control, IntPtr chromeWidgetHostHandle)
{
AssignHandle(chromeWidgetHostHandle);
if (control != null)
{
control.HandleDestroyed += BrowserHandleDestroyed;
}
}
private void BrowserHandleDestroyed(object sender, EventArgs e)
{
ReleaseHandle();
var control = (Control)sender;
control.HandleDestroyed -= BrowserHandleDestroyed;
wndProcHandler = null;
}
/// <summary>
/// Register a Func which is used to intercept <see cref="WndProc(ref Message)"/>
/// calls. <paramref name="wndProcHandler"/> should return true if the message
/// was handled, otherwise false.
/// </summary>
/// <param name="wndProcHandler">Func to be used to intercept messages, null to clear an existing function.</param>
public void OnWndProc(Func<Message, bool> wndProcHandler)
{
this.wndProcHandler = wndProcHandler;
}
/// <inheritdoc/>
protected override void WndProc(ref Message m)
{
var handler = wndProcHandler;
var handled = handler?.Invoke(m);
if (handled == false)
{
base.WndProc(ref m);
}
}
}
}