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

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