How to get a list of open tabs from chrome? | C#

前端 未结 4 984
抹茶落季
抹茶落季 2020-12-03 16:25

So I want to extract the open tabs from google chrome (title, URL) and list theme out kind of like in the chrome task manager. So far I have tried to filter all the chrome p

4条回答
  •  生来不讨喜
    2020-12-03 16:51

    First Reference two dll

    UIAutomationClient.dll
    UIAutomationTypes.dll
    

    Located: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0 (or 3.5)

    Then

    using System.Windows.Automation;
    

    and the code

    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);
          // 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);
          }
       }
    }
    

提交回复
热议问题