Created
July 27, 2024 15:35
-
-
Save hayleyxyz/a83825f2de1d49606b7973cd80ccf98d to your computer and use it in GitHub Desktop.
ProcessWatcher.cs - Watch for process stop/start events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Management; | |
namespace ExplorerHistory | |
{ | |
internal class ProcessWatcher | |
{ | |
private ManagementEventWatcher _startWatch; | |
private ManagementEventWatcher _stopWatch; | |
public ProcessWatcher() | |
{ | |
StartWatch(); | |
} | |
private void StartWatch() | |
{ | |
WqlEventQuery startQuery = new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace"); | |
_startWatch = new ManagementEventWatcher(startQuery); | |
_startWatch.EventArrived += new EventArrivedEventHandler(OnProcessStart); | |
WqlEventQuery stopQuery = new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace"); | |
_stopWatch = new ManagementEventWatcher(stopQuery); | |
_stopWatch.EventArrived += new EventArrivedEventHandler(OnProcessStop); | |
} | |
public void Start() | |
{ | |
_startWatch.Start(); | |
_stopWatch.Start(); | |
} | |
public void Stop() | |
{ | |
_startWatch.Stop(); | |
_stopWatch.Stop(); | |
} | |
private void OnProcessStart(object sender, EventArrivedEventArgs e) | |
{ | |
Console.WriteLine("{0} (PID: {1}) started.", GetProcessNameFromEvent(e), GetProcessIdFromEvent(e)); | |
} | |
private void OnProcessStop(object sender, EventArrivedEventArgs e) | |
{ | |
Console.WriteLine("{0} (PID: {1}) stopped.", GetProcessNameFromEvent(e), GetProcessIdFromEvent(e)); | |
} | |
private int GetProcessIdFromEvent(EventArrivedEventArgs e) | |
{ | |
return Convert.ToInt32(e.NewEvent.Properties["ProcessID"].Value); | |
} | |
private string GetProcessNameFromEvent(EventArrivedEventArgs e) | |
{ | |
return e.NewEvent.Properties["ProcessName"].Value.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment