namespace WindowMonitor
{
using System;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Text.RegularExpressions;
using System.Timers;
///
/// Background service to monitor window status.
///
public partial class WindowMonitorService : ServiceBase
{
///
/// Timer to use to schedule window checks.
///
private Timer timer;
///
/// The window monitor to use.
///
private WindowMonitor monitor;
///
/// The regex to use to extract image names.
///
private Regex filterRegex;
///
/// Initializes a new instance of the class.
///
///
/// The filter to use to extract image names.
///
public WindowMonitorService(string imageFilter)
{
this.InitializeComponent();
this.filterRegex = new Regex(imageFilter);
}
///
/// Starts the service.
///
public void Startup()
{
this.monitor = new WindowMonitor();
this.timer = new Timer(1000);
this.timer.Elapsed += this.OnTimerElapsed;
this.timer.Start();
}
///
/// Stops the service.
///
public void Shutdown()
{
this.timer.Stop();
this.timer.Elapsed -= this.OnTimerElapsed;
this.timer.Dispose();
this.timer = null;
this.monitor = null;
}
///
/// Called when the service is being started by the Windows host.
///
///
/// The arguments given to the service.
///
protected override void OnStart(string[] args)
{
this.Startup();
}
///
/// Called when the service is being stopped by the Windows host.
///
protected override void OnStop()
{
this.Shutdown();
}
///
/// Called when our timer elapses, triggering us to do some work.
///
///
/// The timer that sent the event.
///
///
/// The event arguments.
///
private void OnTimerElapsed(object sender, ElapsedEventArgs e)
{
var handle = this.monitor.GetActiveWindowHandle();
Console.WriteLine(this.monitor.GetWindowTitle(handle));
var fileName = this.monitor.GetWindowFileName(handle);
Console.WriteLine(fileName);
var matches = this.filterRegex.Match(fileName);
var builder = new StringBuilder();
for (var i = 1; i <= matches.Groups.Count; i++)
{
if (builder.Length > 0)
{
builder.Append(' ');
}
builder.Append(matches.Groups[i].Value);
}
Console.WriteLine(builder);
Console.WriteLine();
}
}
}