5

我正在尝试在 Windows 7 上获取所有 USB 设备(包括便携式设备),现在我搜索了所有内容,但没有找到好的答案。

我试过这段代码:

static void Main(string[] args)
{
    //
    // Get an instance of the device manager
    //
    PortableDeviceApiLib.PortableDeviceManagerClass devMgr
        = new PortableDeviceApiLib.PortableDeviceManagerClass();

    //
    // Probe for number of devices
    //
    uint cDevices = 1;
    devMgr.GetDevices(null, ref cDevices);

    //
    // Re-allocate if needed
    //
    if (cDevices > 0)
    {
        string[] deviceIDs = new string[cDevices];
        devMgr.GetDevices(deviceIDs, ref cDevices);

        for (int ndxDevices = 0; ndxDevices < cDevices; ndxDevices++)
        {
            Console.WriteLine("Device[{0}]: {1}",
                    ndxDevices + 1, deviceIDs[ndxDevices]);
        }
    }
    else
    {
        Console.WriteLine("No WPD devices are present!");
    }
}

但我收到此错误:

互操作类型“portabledeviceapilib.portabledevicemanagerclass”无法嵌入

现在我很坚持。

如果您可以帮助我使用此代码/告诉我我应该尝试什么,我会很高兴

我所需要的只是获取连接了哪种类型的 USB,如果连接了手机,还是鼠标。我想知道什么是连接的。

提前感谢

4

2 回答 2

3

我正在使用 NuGet 包PortableDevices(基于Christophe Geers 的教程)。

源自教程的第一部分:

public void ListDevices()
{
    var devices = new PortableDeviceCollection();
    devices.Refresh();

    foreach (var device in devices)
    {
        device.Connect();
        Console.WriteLine(@"DeviceId: {0}, FriendlyName: {1}", device.DeviceId, device.FriendlyName);
        device.Disconnect();
    }
}
于 2016-03-22T08:55:13.120 回答
2

扩展@CodeFox 的答案,并使他的代码ListDevices()正常工作:

  1. 下载 NuGet 包PortableDevices

  2. 添加对这 4 个 COM 库的引用:

    • 便携式设备类扩展
    • PortableDeviceConnectApi
    • 便携式设备类型
    • 便携设备接口
  3. 将dll放在下面obj\Debug并将它们放入bin\Debug

    • Interop.PortableDeviceClassExtension.dll
    • Interop.PortableDeviceConnectApiLib.dll
    • Interop.PortableDeviceTypesLib.dll
    • Interop.PortableDeviceApiLib.dll

现在你可以使用这个函数,虽然FriendlyName它似乎不起作用(它返回一个空字符串):

    private IDictionary<string, string> GetDeviceIds()
    {
        var deviceIds = new Dictionary<string, string>();
        var devices = new PortableDeviceCollection();
        devices.Refresh();
        foreach (var device in devices)
        {
            device.Connect();
            deviceIds.Add(device.FriendlyName, device.DeviceId);
            Console.WriteLine(@"DeviceId: {0}, FriendlyName: {1}", device.DeviceId, device.FriendlyName);
            device.Disconnect();
        }
        return deviceIds;
    }

对我来说,下一步是从设备中获取内容,操作如下:

var contents = device.GetContents();
于 2016-10-02T14:48:36.010 回答