如何从chrome获取打开的标签列表?| C#

use*_*072 4 c# tabs google-chrome

所以我想从谷歌浏览器(标题、URL)中提取打开的标签,并在 chrome 任务管理器中列出主题。到目前为止,我已尝试过滤所有 chrome 进程并获取窗口标题,但这不起作用:

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

这没有给我标签的地址或标题,还有其他方法吗?

Mos*_*fiz 7

先参考两个dll

UIAutomationClient.dll
UIAutomationTypes.dll
Run Code Online (Sandbox Code Playgroud)

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

然后

using System.Windows.Automation;
Run Code Online (Sandbox Code Playgroud)

和代码

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);
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

  • 从已删除的答案中复制评论(来源 Fanari):“错误是由`条件 condNewTab = new PropertyCondition(AutomationElement.NameProperty, "New Tab");` 引起的,它想找到“新标签”,但它不能找到它,对我来说,但我也认为对你来说也是出于以下原因:该字符串已本地化,因此如果您使用的是非英文版 chrome,它将是翻译成该语言的“新标签”字符串。” (2认同)

小智 5

你可以试试这个:

AutomationElement root = AutomationElement.FromHandle(process.MainWindowHandle);
Condition condition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem);
var tabs = root.FindAll(TreeScope.Descendants, condition);
Run Code Online (Sandbox Code Playgroud)