In this article we are going to see how we can create a Windows process monitor using WMI. For this purpose we are going to use ORMi library.
Tradionally, working with WMI to create a tool for this purpose would require that you know WQL and that you have knowledge of how WMI itself works. Using ORMi you can abstract from those requirements and you will find out that this task is extremely easy to accomplish.
First things first. Let's create a Worker Service project:
Second, we have to install ORMi library:
Install-Package ORMi
The next thing we are going to do is create a model which we can use to create a WMI Watcher and that can match the WMI process creation instance.
[WMIClass("Win32_ProcessStartTrace")]
public class Process
{
public string ProcessName { get; set; }
public int ProcessID { get; set; }
}
Note that we created a model that will match the WMI output for a process creation. For that matter we set the WMIClass attribute on the class declaration. We could also do the same on properties.
Then, we are going to register IWMIWatcher so it can be injected via dependency injection where we need it:
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
services.AddSingleton<IWMIWatcher>(new WMIWatcher("root\\CimV2", typeof(Process)));
});
Now we are going to create the business logic. We are going to do all that in the Worker class. For more complex applications you would use a specific service.
public class Worker : BackgroundService
{
private readonly IWMIWatcher _watcher;
public Worker(IWMIWatcher watcher)
{
_watcher = watcher;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_watcher.WMIEventArrived += _watcher_WMIEventArrived;
}
private void _watcher_WMIEventArrived(object sender, WMIEventArgs e)
{
Process process = (Process)e.Object;
Console.WriteLine("New Process: {0} (Pid: {1})", process.ProcessName, process.ProcessID.ToString());
}
}
And that's it!. You will probably need administrator privileges when running the application or debbuging in VS so that the Watcher can do it's job.
Conclusion
The best of using ORMi is to use attributes on classes and property names to make ORMi do all the hard work for you. You see that we haven't wrote any line of WQL code on this example. Nevertheless if you want to write your own queries you also can do it. In fact you can also avoid creating a model and you will receive a dynamic object. It's all up to you.
I hope this article is useful!. If any doubts, fell free to contact me!
Top comments (0)