在C#中枚举Windows便携设备设备、Windows

2023-09-04 01:40:58 作者:不负此生

我试图枚举使用Windows便携设备API和这个API提供的PortableDeviceManager在Windows连接便携设备。

I am attempting to enumerate connected portable devices on Windows using the Windows Portable Devices API and the PortableDeviceManager provided by this API.

我已经实现了设备ID之后MSDN文档链接枚举和各种博客链接,但他们都得到相同的问题 - 我只能把它给我的ID的一个的设备时,有几个连接

I have implemented enumeration of device IDs following the MSDN documentation link and various blogs link, but they all result in the same issue - I can only get it to give me the ID of one device when there are several connected.

下面是C#code我使用的片段:

Here's the snippet of C# code I am using:

PortableDeviceManagerClass deviceManager = new PortableDeviceManagerClass();
deviceManager.RefreshDeviceList();  

uint numberOfDevices = 1;            
deviceManager.GetDevices(null, ref numberOfDevices);

if (numberOfDevices == 0)
{
    return new string[0];
}

string [] deviceIds = new string[numberOfDevices];
deviceManager.GetDevices(ref deviceIds[0], ref numberOfDevices);

return deviceIds;

我有两个设备连接到我的电脑一可拆卸的USB记忆棒和一个数码相机。当两个处于活动状态,我的相机只有设备ID将被退回。当我关闭了摄像头,则返回可拆卸的USB记忆棒的设备ID。

I have two devices connected to my computer, one Removable USB memory stick and one digital camera. When both are active, only the device ID of my camera will be returned. When I deactivate the camera, the device ID of the removable USB stick is returned.

是否有任何人与这个API可以在什么我做错了方向指向我的经历?

Is there anyone with experience with this API which can point me in the direction of what I am doing wrong?

推荐答案

巴丹吉林,

看看下面的帖子由WPD团队,它提到如何修复互操作程序集。

Take a look at the following post by the WPD team, it mentions how you can fix the interop assembly.

http://blogs.msdn.com/b/dimeby8/archive/2006/12/05/enumerating-wpd-devices-in-c.aspx

只要是完整的,我会提到的答案在这里也:

Just to be complete, I'll mention the answer here as well:

这是由于编组限制。此示例code将只检测一个设备。您需要手动修复的interop程序集。

This is due to a marshalling restriction. This sample code will only detect one device. You need to manually fix the interop assembly.

使用命令拆卸PortableDeviceApi Interop程序集:

Disassemble the PortableDeviceApi Interop assembly using the command:

反汇编Interop.PortableDeviceApiLib.dll /out:pdapi.il

在记事本中打开IL和搜索以下字符串:

Open the IL in Notepad and search for the following string:

实例无效GetDevices([中] [出]字符串和放大器;元帅(LPWSTR)pPnPDeviceIDs,

替换上面与下面的字符串该字符串的所有实例:

Replace all instances of the string above with the following string:

实例无效GetDevices([中] [出]字符串[]元帅([])pPnPDeviceIDs,

保存IL和使用命令重新组装的互操作:

Save the IL and reassemble the interop using the command:

ILASM pdapi.il / DLL /output=Interop.PortableDeviceApiLib.dll

重新生成项目。现在,您可以第一个电话 GetDevices NULL 参数来获取设备的数量,然后用一个数组再次调用它获取的设备ID。

Rebuild your project. You can now first call GetDevices with a NULL parameter to get the count of devices and then call it again with an array to get the device IDs.

希望这有助于。