如何使用EnumWindows查找带有特定标题标题的窗口?

如何使用EnumWindows查找带有特定标题标题的窗口?,第1张

如何使用EnumWindows查找带有特定标题/标题的窗口? 原始答案

使用

EnumWindows
并枚举所有窗口,使用
GetWindowText
来获取每个窗口的文本,然后根据需要对其进行过滤。

[Dllimport("user32.dll", CharSet = CharSet.Unipre)]private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);[Dllimport("user32.dll", CharSet = CharSet.Unipre)]private static extern int GetWindowTextLength(IntPtr hWnd);[Dllimport("user32.dll")]private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);// Delegate to filter which windows to include public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);/// <summary> Get the text for the window pointed to by hWnd </summary>public static string GetWindowText(IntPtr hWnd){    int size = GetWindowTextLength(hWnd);    if (size > 0)    {        var builder = new StringBuilder(size + 1);        GetWindowText(hWnd, builder, builder.Capacity);        return builder.ToString();    }    return String.Empty;}/// <summary> Find all windows that match the given filter </summary>/// <param name="filter"> A delegate that returns true for windows///    that should be returned and false for windows that should///    not be returned </param>public static IEnumerable<IntPtr> FindWindows(EnumWindowsProc filter){  IntPtr found = IntPtr.Zero;  List<IntPtr> windows = new List<IntPtr>();  EnumWindows(delegate(IntPtr wnd, IntPtr param)  {      if (filter(wnd, param))      {          // only add the windows that pass the filter          windows.Add(wnd);      }      // but return true here so that we iterate all windows      return true;  }, IntPtr.Zero);  return windows;}/// <summary> Find all windows that contain the given title text </summary>/// <param name="titleText"> The text that the window title must contain. </param>public static IEnumerable<IntPtr> FindWindowsWithText(string titleText){    return FindWindows(delegate(IntPtr wnd, IntPtr param)    {        return GetWindowText(wnd).Contains(titleText);    });}

例如,要获得所有标题中带有“记事本”的窗口:

var windows = FindWindowsWithText("Notepad");
Win32Interop.WinHandles

这个答案非常受欢迎,以至于我创建了一个OSS项目Win32Interop.WinHandles,以为Win32
Windows提供基于IntPtrs的抽象。使用该库,获取标题中包含“记事本”的所有窗口:

var allNotepadWindows   = TopLevelWindowUtils.FindWindows(wh => wh.GetWindowText().Contains("Notepad"));


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5064099.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-16
下一篇 2022-11-16

发表评论

登录后才能评论

评论列表(0条)

保存