使用进程ID获取标签标题/文本

本文关键字:标题 文本 标签 获取 进程 ID | 更新日期: 2023-09-27 18:08:02

我不想使用SetForegroundWindow(),发送键盘键或类似的技术,因为这会导致我的软件出现问题(意外行为)。
我试图找到标题使用欺骗引擎程序(但没有发现任何有用的谷歌浏览器似乎工作"颠倒")。

所以我向前走了一步,使用进程黑客程序,我已经意识到有一个父进程(chrome.exe)进程具有当前活动选项卡的有效窗口句柄,所有其他chrome进程都是它的子进程,又名后台进程(无效窗口句柄)。通过更深入地浏览chrome.exe(父进程)的窗口,我发现窗口句柄的类名是"Chrome_WidgetWin_1"和当前活动选项卡的标题/文本。

这是一张Google Chrome的任务管理器的图片。
我在c#或C或c++中寻找一个函数,它将接受一个整数(进程ID)并返回一个字符串(标签标题/文本)。

static string GetChromeTabTitle(uint processId)
{
    // Assuming I call this function with valid process identifier (PID).
    // What do I do next, here??
}

使用进程ID获取标签标题/文本

我发现最好的方法是使用System.Windows.Automation库。它允许与应用程序交互(主要用于可访问性目的),但您可以将其用于其他目的,例如获得Chrome选项卡。

注意,这将只有工作时,Chrome窗口没有最小化。

这个过程并不简单,如果你想的话,你可以看看我是如何在我自己的项目中做到的,虽然它不是你可以复制粘贴的东西,你会在ChromeTabsFinder中找到你需要的东西:https://github.com/christianrondeau/GoToWindow/blob/master/GoToWindow.Plugins.ExpandBrowsersTabs/Chrome/ChromeTabsFinder.cs

下面是代码(您将需要自动化库):
public IEnumerable<ITab> GetTabsOfWindow(IntPtr hWnd)
{
  var cacheRequest = new CacheRequest();
  cacheRequest.Add(AutomationElement.NameProperty);
  cacheRequest.Add(AutomationElement.LocalizedControlTypeProperty);
  cacheRequest.Add(SelectionItemPattern.Pattern);
  cacheRequest.Add(SelectionItemPattern.SelectionContainerProperty);
  cacheRequest.TreeScope = TreeScope.Element;
  AutomationElement tabBarElement;
  using (cacheRequest.Activate())
  {
    var chromeWindow = AutomationElement.FromHandle(hWnd);
    var mainElement = chromeWindow.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Google Chrome"));
    if (mainElement == null)
      yield break;
    tabBarElement = mainElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "tab"));
  }
  if(tabBarElement == null)
    yield break;
  var tabElements = tabBarElement.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.LocalizedControlTypeProperty, "tab item"));
  for (var tabIndex = 0; tabIndex < tabElements.Count; tabIndex++)
  {
    yield return "Tab: " + tabElements[tabIndex].Current.Name + ", Index: " + tabIndex + 1;
  }
}