F.C.E. 365 Forum
A simple way to detect a specific USB device in C# - Printable Version

+- F.C.E. 365 Forum (https://forum.fce365.info)
+-- Forum: Programming Hub (https://forum.fce365.info/forumdisplay.php?fid=19)
+--- Forum: C# Programming (https://forum.fce365.info/forumdisplay.php?fid=22)
+--- Thread: A simple way to detect a specific USB device in C# (/showthread.php?tid=39)



A simple way to detect a specific USB device in C# - Geosn0w - 12-11-2016

I've been working at some tool lately and I found it very hard to connect to WMI to parse myself the USB devices so that I can check if the one I need was connected, so here is what I managed to do to get my code up and running. 
It detects the USB arrival and removal by overriding WNDPROC method of your form that is inherited from a NativeWindow, we''re checking for a WM_DEVICECHANGE.

You need to add this reference System.Runtime.InteropServices;

Code:
private const int DBT_DEVICEREMOVECOMPLETE = 0x8004;  
private const int WM_DEVICECHANGE = 0x0219;            
private const int DBT_DEVTYP_PORT = 0x00000003;                   
private const int DBT_DEVICEREMOVEPENDING = 0x8003;        
private const int DBT_DEVICEARRIVAL = 0x8000;     
   

protected override void WND(ref Message m)
{
   int devType;
   base.WndProc(ref m);

       switch (m.WParam.ToInt32())
   {
       case DBT_DEVICEARRIVAL:

           devType = Marshal.ReadInt32(m.LParam, 4);
                 
           if (devType == DBT_DEVTYP_PORT)
           {
           label1.Text = "The device was connected";
           }

           break;

          case DBT_DEVICEREMOVECOMPLETE:

          devType = Marshal.ReadInt32(m.LParam, 4);
          if (devType == DBT_DEVTYP_PORT)
          {
           label1.Text = "The device was removed";
          }
          break;
   }
}

This is a code I adapted from an old piece of code found on the internet. I made it so that it updates a label (Label1) when the device event changes.