はじめてのMDbg

Win32プロセスを列挙するにはProcess.GetProcessesを使いますが、Managedプロセスのみ(ついでにAppDomainも)列挙するにはどうすれば良いでしょうか?

そんなときは、MDbgを使うと便利です。MDbgを使うには、

"%NetSamplePath%\bin\MDbgCore.dll"
# デフォルトだとC:\Program Files\Microsoft.NET\SDK\v2.0\bin\MDbgCore.dllかな?

これを自分のプロジェクトにコピーしてコンパイル時に参照してやればOKです。試しに簡単な使用例などを。

using System;
using System.Runtime.InteropServices;

using Microsoft.Samples.Debugging.MdbgEngine;
using Microsoft.Samples.Debugging.CorPublish;
using Microsoft.Samples.Debugging.CorDebug;

public class Program
{
    public static void Main () 
    {
        CorPublish cp = new CorPublish();
        MDbgEngine dbg = new MDbgEngine();

        // Managed Processを列挙
        foreach (CorPublishProcess cpp in cp.EnumProcesses())
        {
            // 自分は除外
            if (System.Diagnostics.Process.GetCurrentProcess().Id != cpp.ProcessId) {
                Console.WriteLine (cpp.DisplayName);
                // Process内のAppDomainを列挙
                foreach (CorPublishAppDomain cpad in cpp.EnumAppDomains()) 
                    Console.WriteLine ("  AppDomain - " + cpad.Name);
            }
        }
    }
}

/*
C:\Program Files\Microsoft FxCop 1.32\fxcop.exe
  AppDomain - fxcop.exe
C:\Home\Bin\reflector\Reflector.exe
  AppDomain - Reflector.exe
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\VCSExpress.exe
  AppDomain - DefaultDomain
 */

こんな感じ。本当はプロセスにアタッチしてモジュール情報とか引っ張り出すつもりだったのですが、デタッチに失敗する(というか、アタッチが上手く行っていない?)ので、挫折しました。(^^;
Object BrowserでMDbgクラス群を見た限りでは、色々面白そうなことが出来そうですね。