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.

WindowMonitorService.cs 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. namespace WindowMonitor
  2. {
  3. using System;
  4. using System.ServiceProcess;
  5. using System.Timers;
  6. /// <summary>
  7. /// Background service to monitor window status.
  8. /// </summary>
  9. public partial class WindowMonitorService : ServiceBase
  10. {
  11. /// <summary>
  12. /// Timer to use to schedule window checks.
  13. /// </summary>
  14. private Timer timer;
  15. /// <summary>
  16. /// The window monitor to use.
  17. /// </summary>
  18. private WindowMonitor monitor;
  19. /// <summary>
  20. /// Initializes a new instance of the <see cref="WindowMonitorService"/> class.
  21. /// </summary>
  22. public WindowMonitorService()
  23. {
  24. this.InitializeComponent();
  25. }
  26. /// <summary>
  27. /// Starts the service.
  28. /// </summary>
  29. public void Startup()
  30. {
  31. this.monitor = new WindowMonitor();
  32. this.timer = new Timer(1000);
  33. this.timer.Elapsed += this.OnTimerElapsed;
  34. this.timer.Start();
  35. }
  36. /// <summary>
  37. /// Stops the service.
  38. /// </summary>
  39. public void Shutdown()
  40. {
  41. this.timer.Stop();
  42. this.timer.Elapsed -= this.OnTimerElapsed;
  43. this.timer.Dispose();
  44. this.timer = null;
  45. this.monitor = null;
  46. }
  47. /// <summary>
  48. /// Called when the service is being started by the Windows host.
  49. /// </summary>
  50. /// <param name="args">
  51. /// The arguments given to the service.
  52. /// </param>
  53. protected override void OnStart(string[] args)
  54. {
  55. this.Startup();
  56. }
  57. /// <summary>
  58. /// Called when the service is being stopped by the Windows host.
  59. /// </summary>
  60. protected override void OnStop()
  61. {
  62. this.Shutdown();
  63. }
  64. /// <summary>
  65. /// Called when our timer elapses, triggering us to do some work.
  66. /// </summary>
  67. /// <param name="sender">
  68. /// The timer that sent the event.
  69. /// </param>
  70. /// <param name="e">
  71. /// The event arguments.
  72. /// </param>
  73. private void OnTimerElapsed(object sender, ElapsedEventArgs e)
  74. {
  75. var handle = this.monitor.GetActiveWindowHandle();
  76. Console.WriteLine(this.monitor.GetWindowTitle(handle));
  77. Console.WriteLine(this.monitor.GetWindowFileName(handle));
  78. Console.WriteLine();
  79. }
  80. }
  81. }