Skip to content

Instantly share code, notes, and snippets.

@kellyelton
Last active February 21, 2017 21:22
Show Gist options
  • Save kellyelton/3822b3db02433829d1f97ddd1fe85be9 to your computer and use it in GitHub Desktop.
Save kellyelton/3822b3db02433829d1f97ddd1fe85be9 to your computer and use it in GitHub Desktop.
Watches for new processes to be run and fires an event when they are.
using System;
using System.Management;
using System.Threading;
namespace KellyElton.Components
{
/// <summary>
/// Watches for new processes to be run and fires an event when they are.
/// </summary>
public class ProcessWatcher : IDisposable
{
public event EventHandler<NewProcessEventArgs> NewProcess;
private readonly ManagementEventWatcher _watcher;
public ProcessWatcher() {
var query = new WqlEventQuery( "__InstanceCreationEvent", new TimeSpan( 0, 0, 0, 0, 100 ), "TargetInstance ISA 'Win32_Process'" );
try {
_watcher = new ManagementEventWatcher( query );
_watcher.EventArrived += new EventArrivedEventHandler( Watcher_EventArrived );
_watcher.Start();
} catch {
_watcher?.Dispose();
throw;
}
}
private void Watcher_EventArrived( object sender, EventArrivedEventArgs e ) {
var mo = (ManagementBaseObject)e.NewEvent["TargetInstance"];
var pm = new Process {
Id = (uint)mo["ProcessId"],
CommandLine = (string)mo["CommandLine"],
};
NewProcess?.Invoke( this, new NewProcessEventArgs {
Process = pm
} );
}
private volatile int _disposedValue;
private bool IsDisposed => Interlocked.CompareExchange( ref _disposedValue, 1, 0 ) != 0;
public void Dispose() {
if( IsDisposed ) return;
if( _watcher != null ) {
_watcher.EventArrived -= new EventArrivedEventHandler( Watcher_EventArrived );
_watcher.Dispose();
}
}
public class NewProcessEventArgs : EventArgs
{
public Process Process { get; set; }
}
public class Process
{
public uint Id { get; set; }
public string CommandLine { get; set; }
public string Name { get; set; }
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment