Click here to Skip to main content
15,889,842 members
Articles / Programming Languages / C#

Process Information and Notifications using WMI

Rate me:
Please Sign up or sign in to vote.
4.73/5 (22 votes)
1 Nov 20053 min read 205.6K   7.8K   79  
An article on WMI.
/***********************************************************************************************
 * File Name	: ProcessInfo.cs
 * Description	: This class demonstrates the use of WMI.
 *				  It provides a static method to query the list of running processes.
 *				  And it provides two events to delegate when an application has been started.
 * 
 * Author		: Asghar Panahy
 * Date			: 26-oct-2005
 ***********************************************************************************************/
using System;
using System.Data;
using System.Management;		

namespace Win32Process
{
	/// <summary>
	/// ProcessInfo class.
	/// </summary>
	public class ProcessInfo
	{
		// defenition of the delegates
		public delegate void StartedEventHandler(object sender, EventArgs e);
		public delegate void TerminatedEventHandler(object sender, EventArgs e);
		
		// events to subscribe
		public StartedEventHandler Started = null; 
		public TerminatedEventHandler Terminated = null; 

		// WMI event watcher
		private ManagementEventWatcher watcher;
		
		// The constructor uses the application name like notepad.exe
		// And it starts the watcher
		public ProcessInfo(string appName)
		{
			// querry every 2 seconds
			string pol = "2"; 

			string queryString = 
				"SELECT *" +
				"  FROM __InstanceOperationEvent " + 
				"WITHIN  " + pol +
				" WHERE TargetInstance ISA 'Win32_Process' "  + 				
				"   AND TargetInstance.Name = '" + appName + "'";
								
			// You could replace the dot by a machine name to watch to that machine
			string scope = @"\\.\root\CIMV2";
			
			// create the watcher and start to listen
			watcher  = new ManagementEventWatcher(scope, queryString);
			watcher.EventArrived += new EventArrivedEventHandler(this.OnEventArrived);			
			watcher.Start();
		}
		public void Dispose()
		{
			watcher.Stop();
			watcher.Dispose();
		}
		public static DataTable RunningProcesses()
		{
			/* One way of constructing a query
			string className = "Win32_Process";
			string condition = "";
			string[] selectedProperties = new string[] {"Name", "ProcessId", "Caption", "ExecutablePath"};
			SelectQuery query = new SelectQuery(className, condition, selectedProperties);
			*/
			
			// The second way of constructing a query
			string queryString = 
				"SELECT Name, ProcessId, Caption, ExecutablePath" + 
				"  FROM Win32_Process";
								
			SelectQuery query = new SelectQuery(queryString);
			ManagementScope scope = new System.Management.ManagementScope(@"\\.\root\CIMV2");
			
			ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
			ManagementObjectCollection processes = searcher.Get();
			
			DataTable result = new DataTable();
			result.Columns.Add("Name", Type.GetType("System.String"));
			result.Columns.Add("ProcessId", Type.GetType("System.Int32"));
			result.Columns.Add("Caption", Type.GetType("System.String"));
			result.Columns.Add("Path", Type.GetType("System.String"));
			
			foreach(ManagementObject mo in processes)
			{
				DataRow row = result.NewRow();
				row["Name"] = mo["Name"].ToString();
				row["ProcessId"] = Convert.ToInt32(mo["ProcessId"]);
				if (mo["Caption"]!= null)
					row["Caption"] = mo["Caption"].ToString();
				if (mo["ExecutablePath"]!= null)
					row["Path"] = mo["ExecutablePath"].ToString();
				result.Rows.Add( row );
			}
			return result;
		} 
		private void OnEventArrived(object sender, System.Management.EventArrivedEventArgs e)
		{
			try 
			{
				string eventName = e.NewEvent.ClassPath.ClassName;

				if (eventName.CompareTo("__InstanceCreationEvent")==0)
				{
					// Started
					if (Started!=null) 
						Started(this, e);
				}
				else if (eventName.CompareTo("__InstanceDeletionEvent")==0)
				{
					// Terminated
					if (Terminated!=null) 
						Terminated(this, e);

				}				
			}
			catch (Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.Message);
			}
		}
		
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Systems Engineer
Netherlands Netherlands
I am a Microsoft certified application developer and work on Microsoft platform since 1993. I like to learn how Microsoft Systems have been built up and dig myself into different libraries in Win32 and .NET. I have worked with C++, VB6, Java, C#, ASP, ASP.Net and PHP.

Comments and Discussions