Selenium Chrome窗口在第二个监视器屏幕上运行,窃取焦点

Sri*_*ngo 11 selenium google-chrome

我使用带有Selenium的Chrome驱动程序2.35的WebDriver.

我有一个双显示器设置,我在其中运行我的测试用例.我大部分时间都无条件地运行我的情况但有时候,当我想调试时,我用浏览器运行它.

窗口打开,我将它拖到我的第二台显示器上,继续使用我的主监视器中的其他东西.但是,只要在二级Chrome Selenium屏幕中有操作,焦点就会转移到该窗口,我将失去控制权.

这真的很烦人,还有其他人遇到过这个问题吗?有解决方案吗

Res*_*cis 0

我建议将窗口位置设置为始终位于底部。在 C# 中,您可以通过如下所示的类来完成此操作:

public static class SetWindowPosition
{
    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
    static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
    private const UInt32 SWP_NOSIZE = 0x0001;
    private const UInt32 SWP_NOMOVE = 0x0002;
    private const UInt32 SWP_NOACTIVATE = 0x0010;

    [DllImport("user32.dll")]
    private static extern bool LockSetForegroundWindow(uint uLockCode);
    private const UInt32 LSFW_LOCK = 1;

    public static void ForceWindowToStayOnBottom(Process process)
    {
        SetWindowPos(
            process.MainWindowHandle, // The handle of the browser window
            HWND_BOTTOM, // Tells it the position, in this case the bottom
            0, 0, 0, 0, // Coordinates for sizing of the window - Will be overriden by NOSIZE
            SWP_NOSIZE | // Says to keep the window its current size
            SWP_NOMOVE | // Says to keep the window in its current spot
            SWP_NOACTIVATE // Activation brings the window to the top, we don't want that
        );

        // If you don't notice this helping, it can probably be deleted.
        // It only deals with other applications and gets automatically undone on user interaction
        LockSetForegroundWindow(
            LSFW_LOCK); // Locks calls to SetForegroundWindow 
    }

    /// <returns> Returns the parent process of each process by the name of processName </returns>
    public static List<Process> GetPrimaryProcesses(string processName) =>

        Process.GetProcesses() // Gets a list of every process on computer
            .Where(process => process.ProcessName.Contains(processName) // Reduces the list to every process by the name we are looking for
                && process.MainWindowHandle != IntPtr.Zero) // Removes any process without a MainWindow (which amounts to every child process)
            .ToList();
}
Run Code Online (Sandbox Code Playgroud)

称为:

SetWindowPosition.ForceWindowToStayOnBottom(
    SetWindowPosition.GetPrimaryProcesses("chrome")[0]);
Run Code Online (Sandbox Code Playgroud)

其中[0]是要最小化的窗口的索引(通常它们按打开的顺序返回)。

其作用与您将窗口设置为 AlwaysOnTop 时可能执行的操作类似(尝试打开任务管理器,单击选项,然后选择“Always On Top”作为示例),只不过方向相反。您应该能够在您喜欢的任何进程上调用它,包括 Web 驱动程序控制台窗口。

如果您想进一步了解其工作原理,我用这两篇文章 ( 1 , 2 ) 以及此处的MSDN 文档来使其工作。