gpt4 book ai didi

c# - 以正确的顺序获取 chrome 标签

转载 作者:太空狗 更新时间:2023-10-30 01:32:54 25 4
gpt4 key购买 nike

我正在尝试按照浏览器标签栏中列出的顺序获取 chrome 标签列表。

这是我的代码:

var automationElements = AutomationElement.FromHandle(proc.MainWindowHandle);

// Find `New Tab` element
var propCondNewTab = new PropertyCondition(AutomationElement.NameProperty, "New Tab");
var elemNewTab = automationElements.FindFirst(TreeScope.Descendants, propCondNewTab);

// Get parent of `New Tab` element
var treeWalker = TreeWalker.ControlViewWalker;
var elemTabStrip = treeWalker.GetParent(elemNewTab);

// Loop through all tabs
var tabItemCondition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem);
foreach (AutomationElement tabItem in elemTabStrip.FindAll(TreeScope.Children, tabItemCondition)) {
var nameProperty = tabItem.GetCurrentPropertyValue(AutomationElement.NameProperty);
Debug.WriteLine("title: " + nameProperty.ToString());
}

但是在 foreach 循环中,标题的顺序与它们在浏览器中的顺序不同。有没有办法让它们按正确的顺序排列?

最佳答案

我不知道获取选项卡顺序的直接方法。您可以做的是获取选项卡矩形的位置,并根据矩形在 X 轴上的位置对选项卡进行排序。

一个非常简单的示例,我在其中使用 SortedDictionary 来保存选项卡及其 X 值。之后,循环遍历字典中的键并提取选项卡项。因为字典是排序的,所以键是有序的,所以列表将按照选项卡在浏览器中显示的顺序排列。

SortedDictionary<double, AutomationElement> orderedTabItems = new SortedDictionary<double, AutomationElement>();

// Loop through all tabs
var tabItemCondition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem);
foreach (AutomationElement tabItem in elemTabStrip.FindAll(TreeScope.Children, tabItemCondition))
{
Rect rectangleProperty = (Rect)tabItem.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
orderedTabItems.Add(rectangleProperty.X, tabItem);
}

for(int i = 0; i < orderedTabItems.Keys.Count; i++)
{
var key = orderedTabItems.Keys.ElementAt(i);
var tabItem = orderedTabItems[key];
var nameProperty = tabItem.GetCurrentPropertyValue(AutomationElement.NameProperty);
Debug.WriteLine("index: " + i + ", title: " + nameProperty.ToString());
}

我确信有更好的解决方案。这是我第一次尝试使用 System.Windows.Automation

编辑: 我忘了说,要访问矩形的 X 属性,您需要添加对 WindowsBase.dll 的引用并在代码中引用它:

using System.Windows;

关于c# - 以正确的顺序获取 chrome 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35598861/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com