我知道这个答案的任何活动已经有一段时间了,但我正在研究一个需要与此类似的功能的项目,我可以告诉你这确实是可能的。据我所知,它确实需要 DDK 并且PInvoke
没有 C# 或 WMI 接口来获取此信息。它需要打开底层 USB 根集线器设备,并直接向它们发送驱动 IOCTL 命令。
好消息是,Microsoft 提供了一个示例 C++ 应用程序,它完全枚举所有 USB 设备并准确显示它们连接到哪些端口。该应用程序是USBView 示例应用程序。
我想你会发现,如果你编译并运行这个应用程序,你会看到它准确地显示了你的设备插入的位置,如果你将任何设备插入该端口,它会显示在同一个地方。如果您创建一个非托管 C++ DLL 提供一些调用,您的 C# 应用程序可以使用这些调用来获取它所需的信息,也许会更容易。
EnumerateHubPorts()
它对代码中的函数有这样的说法:
给定一个开放集线器的句柄和集线器上下游端口的数量,为集线器的每个下游端口发送一个 IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX 请求,以获取有关连接到每个端口的设备(如果有)的信息。
要了解这需要的所有内容(必须从顶部开始枚举所有内容,即使您只对一个端口感兴趣),以下是enum.c
代码中文件顶部列出的注释:
/*
This source file contains the routines which enumerate the USB bus
and populate the TreeView control.
The enumeration process goes like this:
(1) Enumerate Host Controllers and Root Hubs
EnumerateHostControllers()
EnumerateHostController()
Host controllers currently have symbolic link names of the form HCDx,
where x starts at 0. Use CreateFile() to open each host controller
symbolic link. Create a node in the TreeView to represent each host
controller.
GetRootHubName()
After a host controller has been opened, send the host controller an
IOCTL_USB_GET_ROOT_HUB_NAME request to get the symbolic link name of
the root hub that is part of the host controller.
(2) Enumerate Hubs (Root Hubs and External Hubs)
EnumerateHub()
Given the name of a hub, use CreateFile() to map the hub. Send the
hub an IOCTL_USB_GET_NODE_INFORMATION request to get info about the
hub, such as the number of downstream ports. Create a node in the
TreeView to represent each hub.
(3) Enumerate Downstream Ports
EnumerateHubPorts()
Given an handle to an open hub and the number of downstream ports on
the hub, send the hub an IOCTL_USB_GET_NODE_CONNECTION_INFORMATION_EX
request for each downstream port of the hub to get info about the
device (if any) attached to each port. If there is a device attached
to a port, send the hub an IOCTL_USB_GET_NODE_CONNECTION_NAME request
to get the symbolic link name of the hub attached to the downstream
port. If there is a hub attached to the downstream port, recurse to
step (2).
GetAllStringDescriptors()
GetConfigDescriptor()
Create a node in the TreeView to represent each hub port
and attached device.
*/