首页 > 解决方案 > 窗口焦点在最小化/恢复 chrome 浏览器窗口和 chrome 扩展时丢失

问题描述

我创建了 WinForm 应用程序,它的 webBrowser 控件与 Fill 属性对接,并将用户重定向到用户提供的 URL。我正在从 chrome Extension 执行 winForm 进程并获取 chrome 的句柄并将我的子进程的父进程(WinForm)更改为chrome浏览器进程。

当我最小化 chrome 并再次恢复时,我失去了焦点。

但是在切换选项卡或从 Alt+Tab 找到我的 winForm .exe 时,焦点又回来了。

每当用户进入我的活动选项卡时,如何设置我的 .exe 的焦点。

我已经用 C# 编写了应用程序,并使用了非托管代码 SetParent(child handle, parent handle) API 来附加我的 .exe。

我已经尝试过的一些链接:

https://www.codeproject.com/Articles/101367/Code-to-Host-a-Third-Party-Application-in-our-Proc

将窗口停靠在另一个窗口中

在 WPF 窗口中托管外部应用程序

代码片段:

在无限循环中的线程中侦听以下 C# 代码片段以从我的 main.js 获取消息

private void SetAsParent()

{

            try

            {

                Process[] p = Process.GetProcessesByName("chrome");

                foreach (Process item in p)

                {

                    if (!String.IsNullOrEmpty(item.MainWindowTitle))

                    {

                        if (item.MainWindowTitle.Contains("Some Title to match my condition to show the exe...."))

                        {

                            this.Top = 78;

                            this.Left = 0;

                            SetParent(this.Handle, item.MainWindowHandle);

                            this.Visible = true;

                            this.Show();

                            this.Focus();

                            webBrowser.Navigate(some URL);

                            webBrowser.Size = new Size(1366, 979);//dynamic values coming from chrome main.js message via postMessage()

                         }

                    }

                                                                                else

                                                                                {

                                                                                this.Hide();

                                                                                }

                }

                this.Size = new Size(1366, 979);

            }

            catch (Exception ex)

            {

                Debug.WriteLine("Inside Form Load : {0}", ex.Message.ToString());

            }

        }



        [DllImport("user32.dll")]

        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

Chrome 扩展 main.js :

chrome.windows.onFocusChanged.addListener(function() {

chrome.windows.getCurrent(function(window){

    console.log(window.state);

    if(window.state == "normal")

                            {

       Some message to port...

    }

                            else if(window.state == "maximized")

                            {

                                            Focus message to port...

    }

                            else if(window.state == "minimized")

                            {

                                            Minimised message to port....

    }

});

});

预期输出:

在切换选项卡时,焦点会保留,但在最小化和恢复时焦点会丢失。

标签: c#winformsgoogle-chromegoogle-chrome-extension

解决方案


推荐阅读