Search code examples
c#winapidevice-manager

C# - Get last known parent from USB device property details


I want to try read out the last known parent from USB devices in windows 10 with c#, which is visible in device manager -> device properties -> details. I googled a lot and found many solutions to get manufacturer etc., but I was not able to retrieve the wanted information. At Microsoft website I seen, that Win32Pnp Entity class only returns following: https://i.sstatic.net/DCAT7.png

Is there any another way to read the last known parent?

Thanks a lot 🙏🏻 Best regards,

Dave


Solution

  • The "last known parent" property key is undocumented as of today. It's name is DEVPKEY_Device_LastKnownParent and it's value is {83DA6326-97A6-4088-9453-A1923F573B29} 10.

    And Win32_PnPEntity has a GetDeviceProperties method that you can use to read any property using it's key name.

    So, here is a sample console C# code that dumps it (and the friendly name) for all devices in the system:

    foreach (var mo in new ManagementObjectSearcher(null, "SELECT * FROM Win32_PnPEntity").Get().OfType<ManagementObject>())
    {
        // ask for 2 properties
    
        var args = new object[] { new string[] { "DEVPKEY_Device_FriendlyName", "DEVPKEY_Device_LastKnownParent" }, null };
        // or this works too using the PK's value formatted as string
        //var args = new object[] { new string[] { "DEVPKEY_Device_FriendlyName", "{83DA6326-97A6-4088-9453-A1923F573B29} 10" }, null };
    
        // call Win32_PnPEntity.GetDeviceProperties
        mo.InvokeMethod("GetDeviceProperties", args);
    
        var mbos = (ManagementBaseObject[])args[1]; // one mbo for each device property key
    
        var name = mbos[0].Properties.OfType<PropertyData>().FirstOrDefault(p => p.Name == "Data")?.Value;
        if (name != null)
        {
            Console.WriteLine(name);
    
            var parent = mbos[1].Properties.OfType<PropertyData>().FirstOrDefault(p => p.Name == "Data")?.Value;
            Console.WriteLine(" " + parent);
        }
    }