Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell which port a USB device is plugged into?

Tags:

c#

usb

My c# app must manage multiple USB devices which are the identical product from the same manufacturer.

If the user plugs 3 of my devices in, and then unplugs one of them, I need to know which of the 3 devices was unplugged.

However, when I register the devices and receive the WM_DEVICECHANGE notifications, the data returned from the DBT_DEVTYP_DEVICEINTERFACE is identical for each of the devices.

If I could get the USB port info when the devices arrive or are removed it would solve my problem, but I can't find a way to do this.

Any suggestions?

like image 327
Ted N Avatar asked Nov 05 '22 13:11

Ted N


1 Answers

I don't know anything about C#, but in regular C + Win32, you can use the SetupAPI functions to enumerate a bus and probe all of the devices on the bus. If you enumerate the host bridge, you should be able to find your devices in the USB hierarchy. That article I linked to shows you how to use the API, and if you look at the SetupDiGetClassDevs() system call, there is an option for the USB system bus (i.e. parameter 2, "Enumerator").

Also, if you download the Windows Driver Kit, I know it has a sample application that can enumerate the USB bus and provide information about each USB device. The application uses the SetupAPI, and it might serve as a good reference.

I know that Microsoft has gradually exposed the Win32 API as .NET classes, but I'm not sure about this API.

like image 135
Dr. Watson Avatar answered Nov 14 '22 23:11

Dr. Watson