Click here to Skip to main content
Licence CPOL
First Posted 22 Feb 2010
Views 73,974
Downloads 7,317
Bookmarked 204 times

A USB Library to Detect USB Devices

By | 28 Feb 2010 | Article
A USB library to detect USB devices, and manage Attach and Detach events
USBClassLibrary

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

  • 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);
  • 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)
    {
       USBPort.ProcessWindowsMessage(ref m);
    
       base.WndProc(ref m);
    }

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)
    {
       ...
       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

License

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

About the Author

slelong

Other
HP
France France

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionOk thanks I can develope an aplication with USB I review this library PinmemberEliasmrmr16:44 14 Mar '12  
QuestionCan I use software to find the VID & the PID PinmemberLeonHuang072620:08 1 Mar '12  
AnswerRe: Can I use software to find the VID & the PID Pinmemberslelong12:25 3 Mar '12  
GeneralRe: Can I use software to find the VID & the PID PinmemberLeonHuang072621:37 7 Mar '12  
GeneralUsing it in a windows Service Pinmemberalc_aardvark8:46 12 May '11  
GeneralRe: Using it in a windows Service Pinmemberslelong3:12 14 May '11  
GeneralRe: Using it in a windows Service Pinmembermajamer8:57 14 Jun '11  
GeneralOutstanding Pinmembershri_af18:26 20 Feb '11  
GeneralRe: Outstanding Pinmemberslelong20:02 20 Feb '11  
QuestionWPF PinmemberMember 76865322:12 19 Feb '11  
AnswerRe: WPF Pinmemberslelong9:14 19 Feb '11  
SuggestionRe: WPF Pinmembermarkmuetz3:38 8 Aug '11  
GeneralStill not working With FTDI PinmemberFelix Collins16:38 20 Jan '11  
GeneralRe: Still not working With FTDI Pinmemberslelong22:55 21 Jan '11  
GeneralBarcode scanner [modified] PinmemberGrimpozarbre5:52 5 Nov '10  
GeneralA little question Pinmembermecha0316:58 28 Oct '10  
GeneralRe: A little question Pinmemberslelong7:19 31 Oct '10  
QuestionCan we get unique serial number of device ? PinmemberKhaniya20:48 20 Oct '10  
AnswerRe: Can we get unique serial number of device ? Pinmemberslelong1:32 23 Oct '10  
GeneralRe: Can we get unique serial number of device ? PinmemberKhaniya0:02 27 Oct '10  
GeneralRe: Can we get unique serial number of device ? Pinmemberslelong7:13 31 Oct '10  
GeneralRe: Can we get unique serial number of device ? PinmemberFrancesco Giossi6:37 28 Jul '11  
GeneralRe: Can we get unique serial number of device ? Pinmemberwvd_vegt23:24 21 Jun '11  
Generalgot the following problems // NEED HELP Pinmembertherealkasheee20:23 11 Oct '10  
GeneralRe: got the following problems // NEED HELP Pinmemberslelong7:04 12 Oct '10  

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.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 28 Feb 2010
Article Copyright 2010 by slelong
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid