System.Diagnostics.Process class is a managed wrap over a subset of the ToolHelp API – as it enumerates only the process list. Not only that, it will list all the running processes, irrespective of whether they are running unmanaged code or running managed code. What if you wish to identify which of these processes are running managed code?
Unfortunately, neither the ToolHelp API, nor the Process class allow us to identify managed processes from the list they provide us. However, if you have noticed while debugging using Visual Studio, the debugger does identify a managed process in such a list:
So, how does the VS debugger do it?
Well, the CLR exposes debugging interfaces, which contain this functionality. These interfaces include ICorPublish, ICorPublishProcess, ICorPublishAppDomain, just to name a few. Infact, if you have installed the .NET Framework 2.0 SDK and navigate to the %SDKRoot%\v2.0\include folder, you will see the relevant header files that contain these interface definitions
The same identification can now also be done using managed code. Under %SDKRoot%\v2.0\bin folder, you will find, amongst others, MdbgCore.dll - the core of the managed debugger. If you ILASM this file (yes, its an assembly), you will see the managed wraps of the unmanaged interfaces mentioned above:
The starting point is Microsoft.Samples.Debugging.CorPublish.CorPublish. This lets us enumerate the managed processes, returning an instance of Microsoft.Samples.Debugging.CorPublish.CorPublishProcess type. Below is a sample that exemplifies doing the same:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Samples.Debugging.MdbgEngine;
using Microsoft.Samples.Debugging.CorPublish; namespace ManagedProcessList
{
class Program
{
static void Main(string[] args)
{
CorPublish pub = new CorPublish();
foreach (CorPublishProcess proc in pub.EnumProcesses())
{
Console.WriteLine(“{0} IsManaged: {1}”, proc.DisplayName, proc.IsManaged.ToString());
}
}
}
}