2

I have a C# Windows Forms app that runs on Windows 8.1 or newer and does speech recognition. I want to be notified when a new USB audio input device is connected to the system. I am hoping there is a notification service in the Windows API that will tell me when and audio device is connected to the system or disconnected from the system.

Is there such a notification available, or do I have constantly rescan the available audio input devices and create my own notifications when I detect a change? I'd obviously don't want to reinvent the wheel.

Robert Oschler
  • 14,153
  • 18
  • 94
  • 227
  • 1
    [RegisterDeviceNotification](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363431.aspx). Sample code: [Registering for Device Notification](https://msdn.microsoft.com/en-us/library/windows/desktop/aa363432.aspx). – IInspectable Aug 22 '15 at 17:38
  • 1
    http://stackoverflow.com/questions/16245706/check-for-device-change-add-remove-events shows how to listen for USB device insertions or removals. You'd need to then scan to see if it's a USB audio device. – jaket Aug 22 '15 at 21:10

1 Answers1

3

The following will listen for USB plug-in/turn-on un-plug/turn-off at a scan rate of 2seconds intervals

        //turn on USB device event
        WqlEventQuery q_creation = new WqlEventQuery();
        q_creation.EventClassName = "__InstanceCreationEvent";
        q_creation.WithinInterval = new TimeSpan(0, 0, 2);
        q_creation.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'";
        mwe_creation = new ManagementEventWatcher(q_creation);
        mwe_creation.EventArrived += new EventArrivedEventHandler(USBEventArrived_Creation);
        mwe_creation.Start();

        //turn off USB device event
        WqlEventQuery q_deletion = new WqlEventQuery();
        q_deletion.EventClassName = "__InstanceDeletionEvent";
        q_deletion.WithinInterval = new TimeSpan(0, 0, 2);
        q_deletion.Condition = @"TargetInstance ISA 'Win32_USBControllerdevice'  ";
        mwe_deletion = new ManagementEventWatcher(q_deletion);
        mwe_deletion.EventArrived += new EventArrivedEventHandler(USBEventArrived_Deletion);
        mwe_deletion.Start();    

        private void USBEventArrived_Creation(object sender, EventArrivedEventArgs e)
        {
        }

        private void USBEventArrived_Deletion(object sender, EventArrivedEventArgs e)
        {
        }
Tyler Zale
  • 634
  • 1
  • 7
  • 23