53 lines
1.5 KiB
C#
53 lines
1.5 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
using System.Management;
|
|
|
|
#pragma warning disable CA1416
|
|
namespace PowerPlayToggle.Services
|
|
{
|
|
public interface IWMIService : IDisposable
|
|
{
|
|
void WatchForProcess(string processName, Action processStarted, Action processEnded);
|
|
}
|
|
|
|
public class WMIService : IWMIService
|
|
{
|
|
private readonly ManagementEventWatcher startWatcher;
|
|
private readonly ManagementEventWatcher endWatcher;
|
|
|
|
public WMIService()
|
|
{
|
|
startWatcher = new ManagementEventWatcher();
|
|
endWatcher = new ManagementEventWatcher();
|
|
}
|
|
|
|
public void WatchForProcess(string processName, Action processStarted, Action processEnded)
|
|
{
|
|
var filter = $"TargetInstance ISA 'Win32_Process' AND TargetInstance.Name = '{processName}'";
|
|
startWatcher.Query = new WqlEventQuery("__InstanceCreationEvent", new TimeSpan(0,0,1), filter);
|
|
|
|
startWatcher.EventArrived += (sender, e) =>
|
|
{
|
|
processStarted.Invoke();
|
|
};
|
|
startWatcher.Start();
|
|
|
|
endWatcher.Query = new WqlEventQuery("__InstanceDeletionEvent", new TimeSpan(0, 0, 1), filter);
|
|
endWatcher.EventArrived += (sender, e) =>
|
|
{
|
|
processEnded.Invoke();
|
|
};
|
|
endWatcher.Start();
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
startWatcher.Stop();
|
|
endWatcher.Stop();
|
|
}
|
|
}
|
|
}
|