Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 processes and get the window titles but that doesn't work:

var procs = Process.GetProcesses();

...

foreach (var proc in procs)
{
   if (Convert.ToString(proc.ProcessName) == "chrome")
   {
      Console.WriteLine("{0}: {1} | {2} | {3} ||| {4}\n", i, proc.ProcessName, runtime, proc.MainWindowTitle, proc.Handle);
   }
}

This doesn't give me the address or the title of the tab, is there another way to do it?

like image 677
user6879072 Avatar asked Dec 02 '22 14:12

user6879072


1 Answers

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);
      }
   }
}
like image 191
Mostafiz Avatar answered Dec 19 '22 16:12

Mostafiz