How to focus WebView2 in TabControl
I've an application with tabs and in each tab there can be a WebView2 instance. In the WebView2 component of the active tab any random html input element can be currently focused. When i switch between tabs in the TabControl as a user I expect the focus to return to the html element that was previously focused for that tab.
I've made a quick example to show my problem: https://github.com/frankdekker/WebView2RequestFocusExample

- Place the cursor in the input field of the search engine
- Switch to the second tab
- Switch back to the first tab
- I expect the WebView2 to be focused and my cursor be active in the input field
In MainWindow.xaml.cs you can see I request focus to the WebView2 of that tab.
I'm not quite sure what I should do differently. How should I get the WebView2 focused again?
Thanks in advance. Loving WebView2 so far :)
Thanks for the report and the repro app, I was able to repro the behavior as well. I'm changing this to a Bug and I've added it to our backlog to take a closer look.
My workaround for now:
using System;
using System.Runtime.InteropServices;
public static class WebviewFocus
{
private const uint GW_CHILD = 5;
[DllImport("user32.dll")]
private static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[DllImport("user32.dll")]
private static extern IntPtr SetFocus(IntPtr hWnd);
public static void Focus(Microsoft.Web.WebView2.Wpf.WebView2 webview)
{
SetFocus(GetWindow(webview.Handle, GW_CHILD));
}
}
Credits: https://stackoverflow.com/a/66259582/10026704
I'm hitting this as well. The workaround isn't working for me. The webview does get focus when switching to the tab, but it resets the focus to the first element on the web page (Trying to focus again doesn't help as the focus inside the web page was already reset), like that the MoveFocus handler of the webview2 is somehow resetting the focus in the webpage like handling Next instead of Programmatic, unfortunately, WebView2 is closed source and I'm unable to debug any further as this likely an issue in the native code.
Here is another reproduction: https://github.com/segevfiner/WebView2TabTest Basically focus the second input box and switch between the tabs. It will focus the first input box instead of preserving focus on the last focused element between the tabs.