WinForm打开时如何关注WebView2? [英] How to focus on WebView2 when WinForm is opened?

查看:62
本文介绍了WinForm打开时如何关注WebView2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a WinForm app which has just a WebView2 which shows a local website.

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

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.

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

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

推荐答案

这是一个已知问题 已在我测试的最新预发布包 (1.0.790-预发布) 中修复,但不幸的是在此之前的最后一个稳定版本中未修复.因此,如果您使用的是最新的预发布版本,就足以调用:

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

旧版本

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

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

这篇关于WinForm打开时如何关注WebView2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆