Files

101 lines
3.4 KiB
C#

using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
public class MMDevices
{
[ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")]
private class MMDeviceEnumeratorComObject { }
[Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDeviceEnumerator
{
int EnumAudioEndpoints(int dataFlow, int stateMask, out IMMDeviceCollection devices);
int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice device);
int GetDevice(string id, out IMMDevice device);
int RegisterEndpointNotificationCallback(IntPtr client);
int UnregisterEndpointNotificationCallback(IntPtr client);
}
[Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDeviceCollection
{
int GetCount(out int count);
int Item(int index, out IMMDevice device);
}
[Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IMMDevice
{
int Activate(ref Guid iid, int clsCtx, IntPtr activationParams, out IntPtr iface);
int OpenPropertyStore(int access, out IPropertyStore store);
int GetId(out IntPtr id);
int GetState(out int state);
}
[Guid("886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IPropertyStore
{
int GetCount(out int count);
int GetAt(int index, out PROPERTYKEY key);
int GetValue(ref PROPERTYKEY key, out PROPVARIANT value);
int SetValue(ref PROPERTYKEY key, ref PROPVARIANT value);
int Commit();
}
[StructLayout(LayoutKind.Sequential)]
private struct PROPERTYKEY { public Guid fmtid; public int pid; }
[StructLayout(LayoutKind.Explicit)]
private struct PROPVARIANT
{
[FieldOffset(0)] public short vt;
[FieldOffset(8)] public IntPtr pointerValue;
}
private static PROPERTYKEY PKEY_Device_FriendlyName = new PROPERTYKEY
{
fmtid = new Guid("a45c254e-df1c-4efd-8020-67d146a850e0"),
pid = 14
};
public static List<string> List(int dataFlow)
{
return ListWithMask(dataFlow, 1);
}
public static List<string> ListAll(int dataFlow)
{
// 0x0F: active | disabled | notpresent | unplugged
return ListWithMask(dataFlow, 0x0F);
}
public static List<string> ListWithMask(int dataFlow, int mask)
{
var result = new List<string>();
var enumerator = (IMMDeviceEnumerator)(new MMDeviceEnumeratorComObject());
IMMDeviceCollection collection;
if (enumerator.EnumAudioEndpoints(dataFlow, mask, out collection) != 0)
{
result.Add("ERROR: EnumAudioEndpoints failed");
return result;
}
int count;
collection.GetCount(out count);
for (int i = 0; i < count; i++)
{
IMMDevice device;
collection.Item(i, out device);
IPropertyStore store;
device.OpenPropertyStore(0, out store);
PROPVARIANT value;
store.GetValue(ref PKEY_Device_FriendlyName, out value);
string name = Marshal.PtrToStringUni(value.pointerValue);
int state;
device.GetState(out state);
result.Add(name + " | state=" + state);
}
return result;
}
}