Using WMI to monitor process creation, deletion and modification in .NET

WMI is a powerful tool and I have just recently discovered some of its power. Previously I though the only way to detect process creation was by creating a windows hook but now I know it is fairly simple to due with .NET using the Windows.Management namespace. Below is simple ProcessWatcher class that has events that are triggered when a process is created, deleted or modified. Enjoy!

using System;
using System.ComponentModel;
using System.Collections;
using System.Globalization;
using System.Management;

namespace WMI.Win32
{
    public delegate void ProcessEventHandler(Win32_Process proc);
    public class ProcessWatcher : ManagementEventWatcher
    {
        // Process Events
        public event ProcessEventHandler ProcessCreated;
        public event ProcessEventHandler ProcessDeleted;
        public event ProcessEventHandler ProcessModified;

        // WMI WQL process query strings
        static readonly string WMI_OPER_EVENT_QUERY = @"SELECT * FROM 
__InstanceOperationEvent WITHIN 1 WHERE TargetInstance ISA 'Win32_Process'";
        static readonly string WMI_OPER_EVENT_QUERY_WITH_PROC =
            WMI_OPER_EVENT_QUERY + " and TargetInstance.Name = '{0}'";

        public ProcessWatcher()
        {
            Init(string.Empty);
        }
        public ProcessWatcher(string processName)
        {
            Init(processName);
        }
        private void Init(string processName)
        {
            this.Query.QueryLanguage = "WQL";
            if (string.IsNullOrEmpty(processName))
            {
                this.Query.QueryString = WMI_OPER_EVENT_QUERY;
            }
            else
            {
                this.Query.QueryString =
                    string.Format(WMI_OPER_EVENT_QUERY_WITH_PROC, processName);
            }

            this.EventArrived += new EventArrivedEventHandler(watcher_EventArrived);
        }
        private void watcher_EventArrived(object sender, EventArrivedEventArgs e)
        {
            string eventType = e.NewEvent.ClassPath.ClassName;
            Win32_Process proc = new 
                Win32_Process(e.NewEvent["TargetInstance"] as ManagementBaseObject);

            switch (eventType)
            {
                case "__InstanceCreationEvent":
                    if (ProcessCreated != null) ProcessCreated(proc); break;
                case "__InstanceDeletionEvent":
                    if (ProcessDeleted != null) ProcessDeleted(proc); break;
                case "__InstanceModificationEvent":
                    if (ProcessModified != null) ProcessModified(proc); break;
            }
        }
    }

    // Auto-Generated running: mgmtclassgen Win32_Process /n root\cimv2 /o WMI.Win32
    // Renaming the class from Process to Win32_Process
    public class Win32_Process { ... }
}

// Sample Usage
ProcessWatcher procWatcher = new ProcessWatcher("notepad.exe");
procWatcher.ProcessCreated += new ProcessEventHandler(procWatcher_ProcessCreated);
procWatcher.ProcessDeleted += new ProcessEventHandler(procWatcher_ProcessDeleted);
procWatcher.ProcessModified += new ProcessEventHandler(procWatcher_ProcessModified);
procWatcher.Start();

// Do Work

procWatcher.Stop();
Published Saturday, February 11, 2006 2:08 PM by puzzlehacker
Filed under: , ,

Comments

# re: Using WMI to monitor process creation, deletion and modification in .NET

Got this error "No overload for method 'Win32_Process' takes '1' arguments" for the following code:

Win32_Process proc = new Win32_Process(e.NewEvent["TargetInstance"] as ManagementBaseObject);

Wednesday, February 22, 2006 3:39 PM by quakedeus

# re: Using WMI to monitor process creation, deletion and modification in .NET

Never mind. I had the wrong name space!

Thursday, February 23, 2006 12:25 PM by quakedeus

# re: Using WMI to monitor process creation, deletion and modification in .NET

I can not find a definition for Win32_Process class.

Thursday, March 22, 2007 4:24 PM by xmanu

# re: Using WMI to monitor process creation, deletion and modification in .NET

You need to generate by running: mgmtclassgen Win32_Process /n root\cimv2 /o WMI.Win32

and then renaming the class Process to Win32_Process.

Friday, March 23, 2007 1:05 AM by puzzlehacker

# re: Using WMI to monitor process creation, deletion and modification in .NET

Nice article!

Informative and useful..

Wednesday, July 04, 2007 4:50 AM by Johnson

# re: Using WMI to monitor process creation, deletion and modification in .NET

Very helpfull article :)

MSDN documentation of asynchronous event handlers do not describe how to get the actual event instance from the event args.

Do you know if WMI can be used to monitor folder browsing (if i want to capture user history of browsing local folders on his machine, for example) ?

Thursday, July 12, 2007 11:24 AM by Alex

# re: Using WMI to monitor process creation, deletion and modification in .NET

Alex - I don't believe you can use WMI to monitor folder browsing (at least not that I know of). Monitoring folder browsing is really a shell thing, so perhaps you could write a shell extension to do it.

Friday, July 13, 2007 12:51 AM by puzzlehacker

# re: Using WMI to monitor process creation, deletion and modification in .NET

This is a really nice article and seems to do what i need, but I can't seem to get the code working. I generate the code into EventWatchTest namespace as a test, but I seem to just get the error mentioned above:

Got this error "No overload for method 'Win32_Process' takes '1' arguments" for the following code. Also the processCreated event handlers declaration bit doesn't seem to work? Any ideas?

Saturday, July 14, 2007 3:40 AM by Eamonn Jennings

# re: Using WMI to monitor process creation, deletion and modification in .NET

Since you changed the namespace that this code lives in you need to access Win32_Process via it's entire name (i.e. WMI.Win32.Win32_Process) or just include using WMI.Win32.

Sunday, July 15, 2007 10:20 AM by puzzlehacker

# re: Using WMI to monitor process creation, deletion and modification in .NET

I was wondering if you've noticed any massive CPU usage using this?

I'm developing a WLM Addin which monitors when games run/close and set the status accordingly.

Unfortunately, each game thats detected to be installed requires about 5% CPU usage...with 10games installed, half my CPU power is drained!

Sunday, October 07, 2007 4:46 AM by Paul

# links for 2008-02-01 « PaxoBlog

Pingback from  links for 2008-02-01 « PaxoBlog

Friday, February 01, 2008 6:21 PM by links for 2008-02-01 « PaxoBlog

# re: Using WMI to monitor process creation, deletion and modification in .NET

how do u mean auto generated Win32_Process class?

and where to put script "mgmtclassgen Win32_Process /n root\cimv2 /o WMI.Win32" in order to autogenerate? please explain me

Tuesday, May 13, 2008 8:12 AM by civa

# re: Using WMI to monitor process creation, deletion and modification in .NET

Civa - You only need to run "mgmtclassgen Win32_Process /n root\cimv2 /o WMI.Win32" once to generate the class you don't need to generate it every build. I believe you should be able to run it from the VS command prompt.

Tuesday, May 13, 2008 10:59 AM by puzzlehacker

# re: Using WMI to monitor process creation, deletion and modification in .NET

I created a C# project in my solution for ProcessWatcher and I am trying to add access it via VB.NET.  I am trying to add a handler to the ProcessWatcher events in VB and am getting an error when I create my delegate that the Win32.Win32_Process is not CLS compliant. Any ideas on how to fix it?

Friday, July 25, 2008 4:50 PM by RideABike

# re: Using WMI to monitor process creation, deletion and modification in .NET

That is a really well designed class and highly useful. Thanks for sharing.

Yours,

  Alois Kraus

Monday, August 04, 2008 10:16 AM by Alois Kraus

Leave a Comment

(required) 
(required) 
(optional)
(required)