You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#窗口管理:使用Selenium C#做Web自动化时的窗口排列问题

Selenium C# 多窗口平铺排列实现方案

Selenium 内置的窗口控制接口支持直接调整窗口的位置和尺寸,你只需要先获取屏幕的可用分辨率,再根据需要的布局规则计算每个窗口的坐标和宽高,逐个赋值即可实现你要的平铺效果。

  • 前置依赖:需要先安装 NuGet 包 System.Drawing.Common,用于处理坐标和尺寸相关的类型
  • 示例代码(适配2行2列的平铺效果):
using OpenQA.Selenium;
using System.Drawing;
using System.Windows.Forms;

// driver 为你已经初始化完成的 IWebDriver 实例
// 1. 获取主屏幕总分辨率
int screenTotalWidth = Screen.PrimaryScreen.Bounds.Width;
int screenTotalHeight = Screen.PrimaryScreen.Bounds.Height;

// 2. 配置平铺布局参数,2行2列可直接实现四窗口平铺效果
int rows = 2;
int columns = 2;
int perWindowWidth = screenTotalWidth / columns;
int perWindowHeight = screenTotalHeight / rows;

// 3. 获取所有已打开的浏览器窗口句柄
List<string> allWindows = driver.WindowHandles.ToList();

// 4. 遍历调整每个窗口的位置和大小
for (int i = 0; i < allWindows.Count; i++)
{
    driver.SwitchTo().Window(allWindows[i]);
    // 计算当前窗口所在的行列位置
    int currentRow = i / columns;
    int currentColumn = i % columns;
    // 设置窗口左上角坐标
    driver.Manage().Window.Position = new Point(currentColumn * perWindowWidth, currentRow * perWindowHeight);
    // 设置窗口尺寸
    driver.Manage().Window.Size = new Size(perWindowWidth, perWindowHeight);
}

如果你需要调整布局,比如改成1行3列、3行3列等,只需要修改rows和columns的数值即可,其余逻辑无需调整。如果是多显示器场景,将Screen.PrimaryScreen替换为对应显示器的 Screen 实例即可实现指定显示器平铺。非Windows平台运行项目时,需要额外安装 libgdiplus 依赖,同时将 System.Drawing.Common 包版本降级到6.0.x及以下,高版本的该包仅支持Windows系统。

内容的提问来源于stack exchange,提问作者KENLUVX

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 14:54:07