OpenWindowGetter.cs 2.6 KB

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