错误 "Value can't be null",UIAutomationElement

Error "Value can't be null", UIAutomationElement

所以我尝试在 C# 中使用 UIAutomation 从 Chrome 获取所有打开的选项卡,但我不断收到错误消息:

System.ArgumentNullException occurred

HResult=0x80004003
Message=Value can't be NULL.
Source=UIAutomationClient

StackTrace:
at System.Windows.Automation.TreeWalker.GetParent(AutomationElement element)
at chromeTabsTest.Program.Main(String[] args) in C:\Users...\chromeTabsTest\chromeTabsTest\Program.cs:line 31

错误在代码中用注释指出。

    using System;
using System.Diagnostics;
using System.Windows.Automation;

namespace chromeTabsTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Process[] procsChrome = Process.GetProcessesByName("chrome");
            if (procsChrome.Length <= 0)
            {
                Console.WriteLine("Chrome is not running");
            }
            else
            {
                foreach (Process proc in procsChrome)
                {
                    // the chrome process must have a window 
                    if (proc.MainWindowHandle == IntPtr.Zero)
                    {
                        continue;
                    }
                    // to find the tabs we first need to locate something reliable - the 'New Tab' button 
                    AutomationElement root = AutomationElement.FromHandle(proc.MainWindowHandle);
                    Condition condNewTab = new PropertyCondition(AutomationElement.NameProperty, "New Tab");
                    AutomationElement elmNewTab = root.FindFirst(TreeScope.Descendants, condNewTab);
                    // get the tabstrip by getting the parent of the 'new tab' button 
                    TreeWalker treewalker = TreeWalker.ControlViewWalker;
                    AutomationElement elmTabStrip = treewalker.GetParent(elmNewTab); // <------------- Error here 
                    // loop through all the tabs and get the names which is the page title 
                    Condition condTabItem = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem);
                    foreach (AutomationElement tabitem in elmTabStrip.FindAll(TreeScope.Children, condTabItem))
                    {
                        Console.WriteLine(tabitem.Current.Name);
                    }
                }
            }


            Console.Write("\nPress any key to continue...");
            Console.ReadKey();
        }
    }
}

此代码来自另一个 Stack Overflow 问题:

下面这行似乎是语言敏感的:

Condition condNewTab = new PropertyCondition(AutomationElement.NameProperty, "New Tab");

也就是说"New Tab"不是内部字段而是本地化的字符串。这意味着必须更新此行以获得此文本的正确本地化版本。

很有可能有更好的 "locate something reliable" 可以使用,但我对 chrome 自动化不够熟悉,无法说是否有,如果有的话。