WndFinder.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System.Runtime.InteropServices;
  2. using System.Text;
  3. namespace DummyCursor.Spy
  4. {
  5. internal class WndFinder
  6. {
  7. [DllImport("user32.dll", CharSet = CharSet.Unicode)]
  8. private static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
  9. [DllImport("user32.dll", CharSet = CharSet.Unicode)]
  10. private static extern int GetWindowTextLength(IntPtr hWnd);
  11. [DllImport("user32.dll")]
  12. private static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
  13. [DllImport("user32.dll")]
  14. [return: MarshalAs(UnmanagedType.Bool)]
  15. public static extern bool EnumChildWindows(IntPtr hwndParent, EnumWindowsProc lpEnumFunc, IntPtr lParam);
  16. // Delegate to filter which windows to include
  17. public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
  18. /// <summary> Get the text for the window pointed to by hWnd </summary>
  19. public static string GetWindowText(IntPtr hWnd)
  20. {
  21. int size = GetWindowTextLength(hWnd);
  22. if (size > 0)
  23. {
  24. var builder = new StringBuilder(size + 1);
  25. GetWindowText(hWnd, builder, builder.Capacity);
  26. return builder.ToString();
  27. }
  28. return String.Empty;
  29. }
  30. /// <summary> Find all windows that match the given filter </summary>
  31. /// <param name="filter"> A delegate that returns true for windows
  32. /// that should be returned and false for windows that should
  33. /// not be returned </param>
  34. public static IEnumerable<IntPtr> FindWindows(EnumWindowsProc filter)
  35. {
  36. List<IntPtr> windows = new List<IntPtr>();
  37. void EnumChild(IntPtr hWnd, IntPtr lParam)
  38. {
  39. EnumChildWindows(hWnd, delegate (IntPtr hWndChild, IntPtr lParamChild)
  40. {
  41. if (filter(hWndChild, lParam))
  42. {
  43. // only add the windows that pass the filter
  44. windows.Add(hWndChild);
  45. }
  46. EnumChild(hWndChild, lParamChild);
  47. return true;
  48. }, IntPtr.Zero);
  49. }
  50. EnumWindows(delegate (IntPtr wnd, IntPtr param)
  51. {
  52. if (filter(wnd, param))
  53. {
  54. // only add the windows that pass the filter
  55. windows.Add(wnd);
  56. }
  57. EnumChild(wnd, param);
  58. // but return true here so that we iterate all windows
  59. return true;
  60. }, IntPtr.Zero);
  61. return windows;
  62. }
  63. /// <summary> Find all windows that contain the given title text </summary>
  64. /// <param name="titleText"> The text that the window title must contain. </param>
  65. public static IEnumerable<IntPtr> FindWindowsWithText(string titleText)
  66. {
  67. return FindWindows(delegate (IntPtr wnd, IntPtr param)
  68. {
  69. return GetWindowText(wnd).Contains(titleText);
  70. });
  71. }
  72. }
  73. }