Skip to content

Instantly share code, notes, and snippets.

@VictorZhang2014
Created April 30, 2019 09:28
Show Gist options
  • Save VictorZhang2014/a58975a9bc1d530cf7ad6362bfac2fd0 to your computer and use it in GitHub Desktop.
Save VictorZhang2014/a58975a9bc1d530cf7ad6362bfac2fd0 to your computer and use it in GitHub Desktop.
C# Monitor WMI Events
// https://stackoverflow.com/questions/21731044/is-there-a-way-to-attach-an-event-handler-to-the-list-of-running-processes-in-c
//
static void Main(string[] args)
{
var query = new EventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance isa \"Win32_Process\"");
using (var eventWatcher = new ManagementEventWatcher(query))
{
eventWatcher.EventArrived += eventWatcher_EventArrived;
eventWatcher.Start();
Console.WriteLine("Started");
Console.ReadLine();
eventWatcher.EventArrived -= eventWatcher_EventArrived;
eventWatcher.Stop();
}
}
static void eventWatcher_EventArrived(object sender, EventArrivedEventArgs e)
{
try
{
var instanceDescription = e.NewEvent.GetPropertyValue("TargetInstance") as ManagementBaseObject;
if(instanceDescription!=null)
{
var executablePath = instanceDescription.GetPropertyValue("ExecutablePath"); // It may throw an except
if(executablePath!=null)
{
Console.WriteLine("Application {0} started", executablePath.ToString());
}
}
}
catch (ManagementException) { }
}
// https://csharp.hotexamples.com/examples/System.Management/ManagementEventWatcher/WaitForNextEvent/php-managementeventwatcher-waitfornextevent-method-examples.html
//
public static void Run()
{
// Create event query to be notified within 1 second of
// a new process being created
WqlEventQuery query =
new WqlEventQuery("__InstanceCreationEvent",
new TimeSpan(0, 0, 1),
"TargetInstance isa \"Win32_Process\"");
// Initialize an event watcher and subscribe to events
// that match this query
ManagementEventWatcher watcher =
new ManagementEventWatcher(query);
// times out watcher.WaitForNextEvent in 5 seconds
watcher.Options.Timeout = new TimeSpan(0, 0, 5);
// Block until the next event occurs
// Note: this can be done in a loop if waiting for
// more than one occurrence
Console.WriteLine(
"Open an application (notepad.exe) to trigger an event.");
ManagementBaseObject e = watcher.WaitForNextEvent();
log.Debug(e.GetText(TextFormat.Mof ));
ManagementBaseObject target = (ManagementBaseObject)e["TargetInstance"];
Object targetName = target["Name"];
Object targetPath = target["ExecutablePath"];
//Display information from the event
log.Info(
"Process {0} has been created, path is: " + targetName + ", " + targetPath);
//Cancel the subscription
watcher.Stop();
}
@mjanulaitis
Copy link

Any idea's how to get either of these methods to error when the remote server loses network connectivity?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment