How to get Edge window handle (HWND)?

Viewed 2191

I created edge browser window using CreateCoreWebView2Host() method. This method is takes parent window handle and creates child window in which we can navigate the web page. After I am done with navigation I need to return my window handle, which I believe I am failed to return.

On Spy++ I see "Chrome_WidgetWin_0", "Chrome_WidgetWin_1", "Intermediate D3D Window" as child windows to my parent window. which one is the child window handle?I thought I am creating one child window.

I tried by fetching window handles using FindWindowEx() passing above mentioned class names. But still not getting expected results in my project. So I doubt if I am passing correct handle.

Now the question is , How to get the window handle(HWND) for the window created by CreateCoreWebView2Host?

2 Answers

You can get the edge window handle by using GetWindow, passing Handle of WebView2 control to it as the first argument and GW_CHILD as second argument. For exaample:

public const uint GW_CHILD = 5;
[DllImport("user32.dll")]
public static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[DllImport("user32.dll")]
public static extern IntPtr SetFocus(IntPtr hWnd);

WebView2 webView21 = new Microsoft.Web.WebView2.WinForms.WebView2();
private async void Form1_Load(object sender, EventArgs e)
{
    webView21.Dock = DockStyle.Fill;
    this.Controls.Add(webView21);
    await webView21.EnsureCoreWebView2Async();
    webView21.Source = new Uri("https://bing.com");

    webView21.NavigationCompleted += WebView21_NavigationCompleted;
}

private void WebView21_NavigationCompleted(
    object sender, CoreWebView2NavigationCompletedEventArgs e)
{
    var child = GetWindow(webView21.Handle, GW_CHILD);
    SetFocus(child);
}

Note: You may find this GitHub thread useful. This is the trick that I've used to focus the browser in Windows Forms as well.

The WebView2 SDK doesn't provide this HWND because exactly how the WebView2 connects up to the provided parent HWND is intended to be an implementation detail that could change as the underlying Edge browser or WebView2 Runtime is updated even when you stay on the same version of the WebView2 SDK. We're relying in large part on the browser's logic for rendering and so this may change in the future.

Instead of providing an HWND, the CoreWebView2Host (its been renamed to CoreWebView2Controller in more recent SDK releases) provides various methods for you to focus, zoom, and so on. What are you trying to do with the HWND?

Related