WinForm打开时如何关注WebView2?

问题描述

我有一个 WinForm 应用程序,它只有一个显示本地网站的 WebView2。

那个应用程序是从另一个应用程序启动的,一旦它运行,用户就会扫描一些东西,问题是一旦我的应用程序运行,WebView2 就没有焦点,所以当用户扫描他们没有被我处理的项目时网页。

只有在我点击控件后,我才能做我的事情。

应用程序启动后,如何将焦点设置到我的 WebView?

我在表单加载中尝试了以下内容

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();
}

解决方法

这是一个 known issue,它已在我测试的最新预发布包 (1.0.790-prerelease) 中修复,但不幸的是在此之前的最后一个稳定版本中没有。因此,如果您使用的是最新的预发布版本,就足以调用:

webView21.Focus();

旧版本

但作为一种解决方法,您可以订阅NavigationCompleted,然后找到浏览器子窗口并设置焦点:

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);
}