I have a WinForm app which has just a WebView2 which shows a local website.
That application is launched from another application and once it's running the user will scan some stuff, the issue is that once my application runs the WebView2 doesn't have the focus so when the user scans the items they are not processed by my webpage.
Only once i click at the control i'm able to do my stuff.
How can i set the focus to my WebView once the application is launched?
I have tried the following in Form load:
private void Form1_Load(object sender, EventArgs e)
{
webView.Source = new Uri(System.IO.Path.GetDirectoryName(Application.ExecutablePath) + "\\XXXX\\index.html");
TopMost = true;
Focus();
BringToFront();
Activate();
webView.Focus();
}
This is a known issue which has been fixed in the latest prerelease package that I tested (1.0.790-prerelease) but unfortunately not in the last stable release before that. So if you are using the latest prerelease version, that would be enough to call:
webView21.Focus();
Older versions
But as a workaround, you can subscribe to NavigationCompleted
, then find the browser child window and set the focus:
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);
}