首页 > 解决方案 > wpd c#在存在多个设备时枚举设备内容

问题描述

我开发了一个应用程序,它枚举和合并所有连接到系统的驱动器的内容映射。对具有 WPD API Interop.PortableDeviceApiLib.dll 的设备执行相同操作,管理现代设备存在编组限制。

我设法按照https://blogs.msdn.microsoft.com/dimeby8/2006/12/05/enumerating-wpd-devices-in-c/
中引用的技巧 来拆卸和重新组装 Interop.PortableDeviceApiLib。 dll,以便一次管理多个设备,替换

instance void GetDevices([in][out] string& marshal( lpwstr) pPnPDeviceIDs

instance void GetDevices([in][out] string[] marshal( lpwstr[]) pPnPDeviceIDs

但是,对于两个连接的设备,返回数组的第二项总是 null !!!

这是代码片段:

    public string[] Refresh() {
        deviceManager.RefreshDeviceList();
        string[] nullArray = { null };
        uint count = 1;
        try { deviceManager.GetDevices(null, ref count); }    // <-- I tried also with nullArray instead of null
        catch (Exception ex) { Console.WriteLine(ex.Message); count = 0; }
        if (count == 0)
            return null;
        var deviceIds = new string[count];
        deviceManager.GetDevices(deviceIds, ref count);
        foreach (var deviceId in deviceIds)
        {
            Add(new PortableDevice(deviceId));
        }
        return deviceIds;
    }

请注意,有两个已经连接的设备(在每个设备上我都回复了 Allow connection: YES),因此 var count 接收到值 2 并且 deviceIds[0] 是可以的,但是 deviceIds[1] 始终为 null !(即使在交换 USB 插槽上的设备之后)。

我在 Windows 10 上使用 Windows Studio Professional 2017 这两个设备分别是 Honor9 和 U 盘或 iPad。在我插入的 project.csproj 文件中: ...

<Reference Include="Interop.PortableDeviceApiLib">
  <HintPath>.\Interop.PortableDeviceApiLib.dll</HintPath>
</Reference>
<Reference Include="Interop.PortableDeviceTypesLib">
  <HintPath>.\Interop.PortableDeviceTypesLib.dll</HintPath>
</Reference>

...而不是引用 COM 文件:

    <COMReference Include="PortableDeviceApiLib">
  <Guid>{1F001332-1A57-4934-BE31-AFFC99F4EE0A}</Guid>
  <VersionMajor>1</VersionMajor>
  <VersionMinor>0</VersionMinor>
  <Lcid>0</Lcid>
  <WrapperTool>tlbimp</WrapperTool>
  <Isolated>False</Isolated>
  <EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>
<COMReference Include="PortableDeviceTypesLib">
  <Guid>{2B00BA2F-E750-4BEB-9235-97142EDE1D3E}</Guid>
  <VersionMajor>1</VersionMajor>
  <VersionMinor>0</VersionMinor>
  <Lcid>0</Lcid>
  <WrapperTool>tlbimp</WrapperTool>
  <Isolated>False</Isolated>
  <EmbedInteropTypes>False</EmbedInteropTypes>
</COMReference>

因为以前它给了我两个问题:1)每次编译都会覆盖新的 bin/Debug/Interop.PortableDeviceApiLib.dll;2)它给了我一个例外:Impossible to find void PortableDeviceApiLib.IPortableDeviceManager.GetDevices(System.String ByRef, UInt32 ByRef)

有没有人可以解决总是为非第一设备返回的空值?

标签: c#marshallingwpdenumerate-devices

解决方案


推荐阅读