I am trying to get all usb devices(including portable devices) on Windows 7 now I searched all over and didnt find a good answer.
I tried this code:
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!");
}
}
but i get this error:
interop type 'portabledeviceapilib.portabledevicemanagerclass' Cannot be embedded
Now im pretty stuck.
If you could help me with this code/ give me an idea what should i try, ill be happy
all I need is to get which type of USB got connected, if a phone is connected, or a mouse. i want to know what is connected.
Thanx Ahead
To expand on @CodeFox's answer, and in order to make his code ListDevices()
work:
Download the NuGet package PortableDevices
Add references to these 4 COM libraries:
Take the dll's under obj\Debug
and put them into bin\Debug
:
Now you can use this function, although FriendlyName
does not seem to be working (it returns an empty string):
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;
}
The next step for me is getting the contents from the device, which is done like so:
var contents = device.GetContents();
I am using the NuGet package PortableDevices (which is based on the tutorial by Christophe Geers).
Derived from part one of the tutorial:
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With