Programmatically find processes that are using a certain USB device (via device ID) in C#/.NET

Viewed 159

My group and I are working on a C#/.NET program that will display what processes are using the user's webcam and/or microphone (a privacy checker, basically). We're able to display all USB devices and properties about them, such as their device IDs. However, we are struggling to figure out how to look up what processes are using them via the device IDs. We're trying to do something similar to Process Explorer's Find Handle or DLL feature.

Here is the test code we have so far. It displays info about all of the USB devices connected to the computer:

namespace PrivacyHub
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            ManagementObjectCollection collection;
            using (var searcher = new ManagementObjectSearcher(@"Select * from Win32_USBControllerDevice"))
                collection = searcher.Get();

            foreach(var device in collection) {
                string curDeviceInfo = (string)device.GetPropertyValue("Dependent");
                string usbAddress = (curDeviceInfo.Split(new String[] { "DeviceID=" }, 2, StringSplitOptions.None)[1]);

                ManagementObjectCollection devices;
                using (var searcher = new ManagementObjectSearcher("Select * from Win32_PnPEntity where PNPDeviceID = " + usbAddress))
                    devices = searcher.Get();

                foreach(var usbDevice in devices) {
                    Console.WriteLine("----------------DEVICE---------------");
                    foreach(var property in usbDevice.Properties)
                        Console.WriteLine(property.Name + ": " + property.Value);
                    Console.WriteLine("----------------END---------------");
                }

                devices.Dispose();
            }

            
            collection.Dispose();
            
        }
    }
}

I've looked through the Win32 API docs, but I haven't found any info on how to do this. Maybe I'm missing something. Does anyone know how we can programmatically find processes using these devices?

0 Answers
Related