デバイスエニュメレーション

このセクションでは、デバイスの列挙方法、接続されているデバイスの情報取得、およびそれらの接続トポロジーについて説明します。

基本的なデバイス列挙

利用可能なビデオキャプチャデバイスの情報を取得する最も簡単な方法は、DeviceEnum.Devices を参照することです。この静的プロパティは、DeviceInfo オブジェクトのフラットなリストを返します。

以下のコード例では、デバイス一覧を取得し、デバイス情報をコンソールに出力する方法を示しています。

static void PrintDeviceList()
{
    Console.WriteLine("Enumerating all attached video capture devices...");

    var deviceList = ic4.DeviceEnum.Devices;

    if (deviceList.Count == 0)
    {
        Console.WriteLine("No devices found");
    }

    Console.WriteLine($"Found {deviceList.Count} devices:");

    foreach (var deviceInfo in deviceList)
    {
        Console.WriteLine($"\t{FormatDeviceInfo(deviceInfo)}");
    }

    Console.WriteLine();
}

デバイス情報は、シンプルなヘルパー関数を使用して出力されます。

static string FormatDeviceInfo(ic4.DeviceInfo deviceInfo)
{
    return $"Model: {deviceInfo.ModelName} Serial: {deviceInfo.Serial}";
}

インターフェース/デバイストポロジの取得

デバイスの列挙は、インターフェース単位でも実行できます。インターフェースとは、カメラが接続される物理的なハードウェアを指し、USB コントローラやネットワークアダプタなどが該当します。

システムで利用可能なインターフェースの一覧を取得するには、DeviceEnum.Interfaces を参照します。各インターフェースについては、Interface.Devices を使用して、現在接続されているビデオキャプチャデバイスを取得できます。

以下のコードスニペットでは、インターフェースの一覧を取得し、インターフェース情報およびデバイス情報をコンソールに出力する方法を示しています。

static void PrintInterfaceDeviceTree()
{
    Console.WriteLine("Enumerating video capture devices by interface...");

    var interfaceList = ic4.DeviceEnum.Interfaces.ToList();

    foreach (var itf in interfaceList)
    {
        Console.WriteLine($"Interface: {itf.DisplayName}");
        Console.Write($"\tProvided by {itf.TransportLayerName}");
        Console.WriteLine($" [TLType: {itf.TransportLayerType}]");

        var deviceList = itf.Devices.ToList();

        if (deviceList.Count == 0)
        {
            Console.WriteLine("\tNo devices found");
        }

        Console.WriteLine($"\tFound {deviceList.Count} devices:");

        foreach (var deviceInfo in deviceList)
        {
            Console.WriteLine($"\t\t{FormatDeviceInfo(deviceInfo)}");
        }
    }

    Console.WriteLine();
}

デバイスの接続/切断通知を受け取る

DeviceEnum オブジェクトでは、利用可能なデバイス一覧の変更をプログラムに通知するためのイベントハンドラを登録できます。接続されているデバイスの変更を検知するには、DeviceEnum.DeviceListChanged にメソッドを割り当てます。

以下のコードスニペットでは、デバイス一覧変更イベントハンドラを登録し、最後に解除する方法を示しています。

static void RegisterDeviceListChanged()
{
    var enumerator = new ic4.DeviceEnum();
    enumerator.DeviceListChanged += HandleDeviceListChanged;

    Console.WriteLine("Waiting for DeviceListChanged event");
    Console.WriteLine("Press any key to exit");
    Console.ReadKey();
}

デバイス一覧変更時のイベントハンドラの例を以下に示します。

static void HandleDeviceListChanged(object sender, EventArgs e)
{
    Console.WriteLine("Device list changed!");
    PrintDeviceList();
}