A simple way to detect a specific USB device in C#
#1
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.
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)

About Us
    Welcome to F.C.E. 365 Forum! This forum is a place where you can discuss technology at its finest. We provide you a place to ask questions or to read / watch various tech-related tutorials.