How to detect USB overcurrent in C#?

MateoProgramistaZaDyche 1 Reputation point
2021-08-16T02:41:08.803+00:00

Hi,

I dig the whole internet and I can't find the answer to how to detect USB device overcurrent? I want to display it in textBox with a USB device name or Hub name where the overcurrent occurs. I'm interested only in c#.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,828 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,247 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Jack J Jun 24,286 Reputation points Microsoft Vendor
    2021-08-16T06:57:35.507+00:00

    @MateoProgramistaZaDyche , you could try to use WMI to detect the USB device when the USB device is inserted in your computer.

    Here is a code example you could refer to.

    using System.Management;  
      public Form1()  
            {  
                InitializeComponent();  
                backgroundWorker1.RunWorkerAsync();  
                TextBox.CheckForIllegalCrossThreadCalls = false;  
            }  
     private void Watcher_EventArrived(object sender, EventArrivedEventArgs e)  
            {  
                ManagementBaseObject instance = (ManagementBaseObject)e.NewEvent["TargetInstance"];  
                string result = "Device Name is " + instance.Properties["Name"].Value.ToString();  
                textBox1.Text = result;  
                Console.WriteLine("inserted");  
            }  
      
            private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)  
            {  
                ManagementEventWatcher watcher = new ManagementEventWatcher();  
                WqlEventQuery query = new WqlEventQuery("SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA 'Win32_USBHub'");  
                watcher.EventArrived += Watcher_EventArrived;  
                watcher.Query = query;  
                watcher.Start();  
                watcher.WaitForNextEvent();  
            }  
    

    Based on my test, I could detect the mouse and keyboard USB Device when I inserted the device to the computer.

    123492-screenshot-2021-08-16-145706.png


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments