Click here to Skip to main content
Click here to Skip to main content

A USB Library to Detect USB Devices

, 4 Feb 2014
Rate this:
Please Sign up or sign in to vote.
A USB library to detect USB devices, and manage Attach and Detach events

USB Class Library WPF Demo


Introduction 

This article is about a USB library which enables you to manage Attach and Detach events of USB devices and detect your own device. I was not able to find a working code written in C# and which runs under both Windows XP and Windows 7 x64. I therefore decided to write my own code. I read various articles about USB Attach and Detach detection, and got some help from both the Microsoft website and the PINVOKE.NET website (http://www.pinvoke.net).

This code is a separate module that you can link to your own project. The code explains how to add additional properties.

Using the Code

Updating your Code

Windows Forms 

  • Add a reference to your project.
  • Add the using directive in your code:
    using USBClassLibrary;
  • Declare an instance of USBClass.
    private USBClassLibrary.USBClass USBPort;
  • Declare an instance of the DeviceProperties class if you want to read the properties of your devices.
    private USBClassLibrary.USBClass.DeviceProperties USBDeviceProperties;
  • Create an instance of the USBClass class.
    USBPort = new USBClass();
  • Create an instance of the DeviceProperties class.
    USBDeviceProperties = new USBClass.DeviceProperties(); 
  • Add handlers for the events exposed by the USBClass class.
    USBPort.USBDeviceAttached += new USBClass.USBDeviceEventHandler(USBPort_USBDeviceAttached);
    USBPort.USBDeviceRemoved += new USBClass.USBDeviceEventHandler(USBPort_USBDeviceRemoved);
  • Register your form to receive Windows messages when devices are added or removed.
    USBPort.RegisterForDeviceChange(true, this.Handle);
  • Then, check if your device is not already connected:
    if (USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
                 ref USBDeviceProperties, false))
    {
       //My Device is connected
       MyUSBDeviceConnected = true;
    }
  • Implement Attach and Detach handlers:
    private void USBPort_USBDeviceAttached(object sender, 
                 USBClass.USBDeviceEventArgs e)
    {
       if (!MyUSBDeviceConnected)
       {
          if (USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
                                    ref USBDeviceProperties, false))
          {
             //My Device is connected
             MyUSBDeviceConnected = true;
          }
       }
    }
    
    private void USBPort_USBDeviceRemoved(object sender, 
                 USBClass.USBDeviceEventArgs e)
    {
       if (!USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
                                  ref USBDeviceProperties, false))
       {
          //My Device is removed
          MyUSBDeviceConnected = false;
       }
    }
  • Handle Windows message in your form to pass them to the USBClass class:
    protected override void WndProc(ref Message m)
    {
       bool IsHandled = false;
    
       USBPort.ProcessWindowsMessage(m.Msg, m.WParam, m.LParam, ref IsHandled);
    
       base.WndProc(ref m);
    }

WPF 

  • Add a reference to your project.
  • Add the using directive in your code:
    using USBClassLibrary;
  • Declare an instance of USBClass.
    private USBClassLibrary.USBClass USBPort;
  • Declare an instance of the DeviceProperties class if you want to read the properties of your devices.
    private USBClassLibrary.USBClass.DeviceProperties USBDeviceProperties;
  • Create an instance of the USBClass class.
    USBPort = new USBClass();
  • Create an instance of the DeviceProperties class.
    USBDeviceProperties = new USBClass.DeviceProperties(); 
  • Add handlers for the events exposed by the USBClass class.
    USBPort.USBDeviceAttached += new USBClass.USBDeviceEventHandler(USBPort_USBDeviceAttached);
    USBPort.USBDeviceRemoved += new USBClass.USBDeviceEventHandler(USBPort_USBDeviceRemoved);
  • Override OnSourceInitialized in order to:
    • Retrieve the Windows Handle
    • Add an event handler that receives all window messages
    • Register your form to receive Windows messages when devices are added or removed 
  • protected override void OnSourceInitialized(EventArgs e)
    {
       base.OnSourceInitialized(e);
       HwndSource source = PresentationSource.FromVisual(this) as HwndSource;
       source.AddHook(WndProc);
    
       //USB Connection
       USBPort.RegisterForDeviceChange(true, source.Handle);
       USBTryMyDeviceConnection();
       MyUSBDeviceConnected = false;
    } 
  • Handle Windows message in your form to pass them to the USBClass class
    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
       USBPort.ProcessWindowsMessage(msg, wParam, lParam, ref handled);
                
       return IntPtr.Zero;
    }
    
  • Then, check if your device is not already connected:
  • if (USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
                 ref USBDeviceProperties, false))
    {
       //My Device is connected
       MyUSBDeviceConnected = true;
    }
  • Implement Attach and Detach handlers:
    private void USBPort_USBDeviceAttached(object sender, 
                 USBClass.USBDeviceEventArgs e)
    {
       if (!MyUSBDeviceConnected)
       {
          if (USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
                                    ref USBDeviceProperties, false))
          {
             //My Device is connected
             MyUSBDeviceConnected = true;
          }
       }
    }
    
    private void USBPort_USBDeviceRemoved(object sender, 
                 USBClass.USBDeviceEventArgs e)
    {
       if (!USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
                                  ref USBDeviceProperties, false))
       {
          //My Device is removed
          MyUSBDeviceConnected = false;
       }
    } 

Getting the COM Port Associated to a USB Device

If your device emulates a Serial Port, then you can retrieve its COM Port.

The GetUSBDevice function has a fourth parameter GetCOMPort:

public static bool GetUSBDevice
	(UInt32 VID, UInt32 PID, ref DeviceProperties DP, bool GetCOMPort)

Set its value to True in your connection code and retrieve the COM Port from the DeviceProperties structure:

if (USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
             ref USBDeviceProperties, true))
{
   String COMPort;

   //My Device is connected
   MyUSBDeviceConnected = true;
   COMPort = DP.COMPort;
}

Compiling

In the project properties, Build tab, do not select Any CPU in the "Platform target" drop down list, pick up x86 or x64.

Updating the Code

If you need to read other device properties, simply update the code as follows:

  • Look up the SetupDiGetDeviceRegistryProperty function in MSDN and find the property you want to get.
  • Add a new variable to the DeviceProperties matching the characteristics of your property:
    public struct DeviceProperties
    {
       public string FriendlyName;
       public string DeviceDescription;
       public string DeviceType;
       public string DeviceManufacturer;
       public string DeviceClass;
       public string DeviceLocation;
       public string DevicePath;
       public string DevicePhysicalObjectName;
       public string COMPort;
    }
  • Update the GetUSBDevice function:
    public static bool GetUSBDevice(UInt32 VID, UInt32 PID, ref DeviceProperties DP, bool GetCOMPort)
    {
       ...
        DP.DevicePhysicalObjectName = String.Empty;
        if (Win32Wrapper.SetupDiGetDeviceRegistryProperty(h, ref DevInfoData, 
          (UInt32)Win32Wrapper.SPDRP.SPDRP_PHYSICAL_DEVICE_OBJECT_NAME, 
          ref RegType, intptrBuffer, BUFFER_SIZE, ref RequiredSize))
        {
          DP.DevicePhysicalObjectName = Marshal.PtrToStringAuto(intptrBuffer);
        }
        ...
    }

History

  • Feb 22, 2010
    • Article first published
  • Feb 26, 2010
    • Added code to retrieve the COM Port associated to USB Devices emulating a serial port
    • Updated documentation accordingly
  •  November 17, 2013
    • Added support to detect composite devices and fixed a bug where DeviceProperties strings were not intialized correctly. 
    • Updated Demo application by adding a "MI" field.
  • February 5, 2014
    • Added support for WPF applications: the USB Class Library is modified to remove any reference to Windows Forms specific objects. 
    • The code works on Windows 8 and Windows 8.1 too 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

slelong
Other HP
France France
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 Pinmembersoulprovidergr6-Nov-12 3:51 
GeneralRe: My vote of 5 Pinmemberslelong8-Nov-12 19:47 
GeneralRe: My vote of 5 Pinmembersoulprovidergr8-Nov-12 23:26 
GeneralRe: My vote of 5 Pinmemberslelong9-Nov-12 7:27 
GeneralRe: My vote of 5 PinmemberMember 968537218-Dec-12 22:32 
GeneralRe: My vote of 5 Pinmemberslelong18-Dec-12 22:34 
GeneralMy vote of 1 PinmemberLavrekho16-Oct-12 9:56 
QuestionRead and Write data from USB device Pinmemberjeedigunta24-Jul-12 19:23 
Hi..
 
This is very good example but i want to read to read data from usb device and write data to USB pls help in this regard
QuestionOk thanks I can develope an aplication with USB I review this library PinmemberEliasmrmr14-Mar-12 16:44 
QuestionCan I use software to find the VID & the PID PinmemberLeonHuang07261-Mar-12 20:08 
AnswerRe: Can I use software to find the VID & the PID Pinmemberslelong3-Mar-12 12:25 
GeneralRe: Can I use software to find the VID & the PID PinmemberLeonHuang07267-Mar-12 21:37 
GeneralRe: Can I use software to find the VID & the PID Pinmemberlandersohn694-Jun-12 5:45 
GeneralUsing it in a windows Service Pinmemberalc_aardvark12-May-11 8:46 
GeneralRe: Using it in a windows Service Pinmemberslelong14-May-11 3:12 
GeneralRe: Using it in a windows Service Pinmembermajamer14-Jun-11 8:57 
GeneralOutstanding Pinmembershri_af20-Feb-11 18:26 
GeneralRe: Outstanding Pinmemberslelong20-Feb-11 20:02 
QuestionWPF PinmemberMember 768653219-Feb-11 2:12 
AnswerRe: WPF Pinmemberslelong19-Feb-11 9:14 
SuggestionRe: WPF Pinmembermarkmuetz8-Aug-11 3:38 
GeneralStill not working With FTDI PinmemberFelix Collins20-Jan-11 16:38 
GeneralRe: Still not working With FTDI Pinmemberslelong21-Jan-11 22:55 
GeneralBarcode scanner [modified] PinmemberGrimpozarbre5-Nov-10 5:52 
GeneralA little question Pinmembermecha0328-Oct-10 16:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 5 Feb 2014
Article Copyright 2010 by slelong
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid