C# app to record currently focused window
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WindowMonitor.cs 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. namespace WindowMonitor
  2. {
  3. using System;
  4. using System.Management;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. /// <summary>
  8. /// Utility class to monitor the currently active window.
  9. /// </summary>
  10. public class WindowMonitor
  11. {
  12. /// <summary>
  13. /// Gets a pointer to the currently active window.
  14. /// </summary>
  15. /// <returns>
  16. /// A pointer to the active window.
  17. /// </returns>
  18. public IntPtr GetActiveWindowHandle()
  19. {
  20. return GetForegroundWindow();
  21. }
  22. /// <summary>
  23. /// Gets the title of the window with the given handle.
  24. /// </summary>
  25. /// <param name="handle">
  26. /// The handle of the window to look up.
  27. /// </param>
  28. /// <returns>
  29. /// The textual title of the given window.
  30. /// </returns>
  31. public string GetWindowTitle(IntPtr handle)
  32. {
  33. var length = GetWindowTextLength(handle);
  34. var buffer = new StringBuilder(length + 1);
  35. GetWindowText(handle, buffer, length + 1);
  36. return buffer.ToString();
  37. }
  38. /// <summary>
  39. /// Gets the full command line of the process that owns the window
  40. /// with the given handle.
  41. /// </summary>
  42. /// <param name="handle">
  43. /// The handle of the window to look up.
  44. /// </param>
  45. /// <returns>
  46. /// The command line of the owning process, or <c>string.Empty</c> if
  47. /// it couldn't be found.
  48. /// </returns>
  49. public string GetWindowFileName(IntPtr handle)
  50. {
  51. int processId;
  52. GetWindowThreadProcessId(handle, out processId);
  53. if (processId == 0)
  54. {
  55. return string.Empty;
  56. }
  57. var wmiQuery = string.Format("select CommandLine from Win32_Process where ProcessId={0}", processId);
  58. var searcher = new ManagementObjectSearcher(wmiQuery);
  59. var resultEnumerator = searcher.Get().GetEnumerator();
  60. return resultEnumerator.MoveNext() ? resultEnumerator.Current["CommandLine"].ToString() : string.Empty;
  61. }
  62. [DllImport("user32.dll")]
  63. private static extern IntPtr GetForegroundWindow();
  64. [DllImport("user32.dll")]
  65. private static extern int GetWindowTextLength(IntPtr handle);
  66. [DllImport("user32.dll")]
  67. private static extern int GetWindowText(IntPtr handle, StringBuilder text, int count);
  68. [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  69. private static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
  70. }
  71. }