OpenWindowGetter.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Diagnostics;
  2. using System.Runtime.InteropServices;
  3. using System.Text;
  4. using HWND = System.IntPtr;
  5. namespace InABox.WPF
  6. {
  7. /// <summary>Contains functionality to get all the open windows.</summary>
  8. public static class OpenWindowGetter
  9. {
  10. [DllImport("USER32.DLL")]
  11. private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);
  12. [DllImport("USER32.DLL")]
  13. private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);
  14. [DllImport("USER32.DLL")]
  15. private static extern int GetWindowTextLength(HWND hWnd);
  16. [DllImport("USER32.DLL")]
  17. private static extern bool IsWindowVisible(HWND hWnd);
  18. [DllImport("USER32.DLL")]
  19. private static extern IntPtr GetShellWindow();
  20. [DllImport("user32.dll")]
  21. private static extern IntPtr GetForegroundWindow();
  22. [DllImport("user32")]
  23. private static extern uint GetWindowThreadProcessId(HWND hWnd, out int lpdwProcessId);
  24. /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
  25. /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
  26. public static IDictionary<HWND, string> GetOpenWindows()
  27. {
  28. var shellWindow = GetShellWindow();
  29. var windows = new Dictionary<HWND, string>();
  30. EnumWindows(delegate(HWND hWnd, int lParam)
  31. {
  32. if (hWnd == shellWindow) return true;
  33. if (!IsWindowVisible(hWnd)) return true;
  34. var length = GetWindowTextLength(hWnd);
  35. if (length == 0) return true;
  36. var builder = new StringBuilder(length);
  37. GetWindowText(hWnd, builder, length + 1);
  38. windows[hWnd] = builder.ToString();
  39. return true;
  40. }, 0);
  41. return windows;
  42. }
  43. public static string GetActiveWindowTitle()
  44. {
  45. const int nChars = 256;
  46. var Buff = new StringBuilder(nChars);
  47. var handle = GetForegroundWindow();
  48. if (GetWindowText(handle, Buff, nChars) > 0) return Buff.ToString();
  49. return null;
  50. }
  51. public static string GetActiveWindowProcess()
  52. {
  53. var handle = GetForegroundWindow();
  54. GetWindowThreadProcessId(handle, out var pid);
  55. var p = Process.GetProcessById(pid);
  56. return p?.ProcessName;
  57. }
  58. private delegate bool EnumWindowsProc(HWND hWnd, int lParam);
  59. }
  60. }