Click here to Skip to main content
12,449,325 members (59,324 online)
Click here to Skip to main content
Add your own
alternative version

Stats

308.7K views
54.8K downloads
401 bookmarked
Posted

A USB Library to Detect USB Devices

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

 

 

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 List<T> of DeviceProperties if you want to read the properties of your devices.
    private List<USBClassLibrary.USBClass.DeviceProperties> ListOfUSBDeviceProperties;
  • Create an instance of the USBClass class.
    USBPort = new USBClass();
  • Create an instance List<T> of DeviceProperties class.
    ListOfUSBDeviceProperties = new List<USBClassLibrary.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 ListOfUSBDeviceProperties, 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 ListOfUSBDeviceProperties, false))
          {
             //My Device is connected
             MyUSBDeviceConnected = true;
          }
       }
    }
    private void USBPort_USBDeviceRemoved(object sender, 
                 USBClass.USBDeviceEventArgs e)
    {
       if (!USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
                                  ref ListOfUSBDeviceProperties, 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 List<T> of the DeviceProperties class if you want to read the properties of your devices.
    private List<USBClassLibrary.USBClass.DeviceProperties> ListOfUSBDeviceProperties;
  • Create an instance of the USBClass class.
    USBPort = new USBClass();
  • Create an instance List<T> of the DeviceProperties class.
    ListOfUSBDeviceProperties = new List<USBClassLibrary.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 ListOfUSBDeviceProperties, 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 ListOfUSBDeviceProperties, false))
          {
             //My Device is connected
             MyUSBDeviceConnected = true;
          }
       }
    }
    private void USBPort_USBDeviceRemoved(object sender, 
                 USBClass.USBDeviceEventArgs e)
    {
       if (!USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
                                  ref ListOfUSBDeviceProperties, 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 List<deviceproperties> ListOfDP, bool GetCOMPort, Nullable<uint32> MI=null)

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

if (USBClass.GetUSBDevice(MyDeviceVID, MyDevicePID, 
             ref ListOfUSBDeviceProperties, 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 List<deviceproperties> ListOfDP, bool GetCOMPort, Nullable<uint32> MI=null)
    {
       ...
        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 
  • September 21, 2014
    • Added the capability to identify more than 1 identical devices returning an array of Device Properties.

 

 

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

You may also be interested in...

Pro
Pro

Comments and Discussions

 
QuestionFTDI .. not detected well Pin
Member 1094240416-Mar-16 15:45
memberMember 1094240416-Mar-16 15:45 
QuestionNOT WORKING WELL WITH FTDI COM PORT Pin
Member 1094240416-Mar-16 14:38
memberMember 1094240416-Mar-16 14:38 
AnswerRe: NOT WORKING WELL WITH FTDI COM PORT Pin
nick70328-Apr-16 4:25
membernick70328-Apr-16 4:25 
Questiondont work with VB.NET Pin
buddhafragt17-Dec-15 13:27
memberbuddhafragt17-Dec-15 13:27 
QuestionDisconnected! Pin
pip01024-Sep-15 1:16
memberpip01024-Sep-15 1:16 
AnswerRe: Disconnected! Pin
Member 1030193015-Dec-15 8:46
memberMember 1030193015-Dec-15 8:46 
GeneralRe: Disconnected! Pin
pip01019-Jan-16 23:44
memberpip01019-Jan-16 23:44 
QuestionUSBClassLibrary Device ID or Serial Number (re-submitted) Pin
Member 1198310921-Sep-15 2:39
memberMember 1198310921-Sep-15 2:39 
BugError Compiling Pin
Member 119723659-Sep-15 13:36
memberMember 119723659-Sep-15 13:36 
Questionevents always fire twice Pin
jvdub2227-May-15 8:59
memberjvdub2227-May-15 8:59 
QuestionI am not found library USB Pin
Member 245846719-May-15 20:31
memberMember 245846719-May-15 20:31 
Questioni don't find usb library.csproj Pin
Member 984112527-Mar-15 9:26
memberMember 984112527-Mar-15 9:26 
QuestionWhat reference do I add? Pin
Member 1145076616-Feb-15 4:14
memberMember 1145076616-Feb-15 4:14 
QuestionI don't found the USBClassLibrary.dll file Pin
Armando Flores26-Jan-15 7:24
memberArmando Flores26-Jan-15 7:24 
AnswerRe: I don't found the USBClassLibrary.dll file Pin
Member 1102529828-Feb-15 5:11
memberMember 1102529828-Feb-15 5:11 
QuestionNuGet Pin
Robin Jones14-Nov-14 4:31
memberRobin Jones14-Nov-14 4:31 
AnswerRe: NuGet Pin
slelong16-Nov-14 8:45
memberslelong16-Nov-14 8:45 
GeneralRe: NuGet Pin
Robin Jones16-Nov-14 10:04
memberRobin Jones16-Nov-14 10:04 
BugRetargeting for x64 causes an exception (with fix) Pin
Robin Jones18-Oct-14 10:39
memberRobin Jones18-Oct-14 10:39 
GeneralRe: Retargeting for x64 causes an exception (with fix) Pin
slelong18-Oct-14 21:27
memberslelong18-Oct-14 21:27 
GeneralRe: Retargeting for x64 causes an exception (with fix) Pin
Robin Jones14-Nov-14 4:24
memberRobin Jones14-Nov-14 4:24 
QuestionError while compiling Pin
Member 108518668-Oct-14 1:14
memberMember 108518668-Oct-14 1:14 
AnswerRe: Error while compiling Pin
slelong8-Oct-14 3:00
memberslelong8-Oct-14 3:00 
GeneralRe: Error while compiling Pin
Member 108518668-Oct-14 3:15
memberMember 108518668-Oct-14 3:15 
GeneralRe: Error while compiling Pin
slelong8-Oct-14 3:56
memberslelong8-Oct-14 3:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    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 | Terms of Use | Mobile
Web01 | 2.8.160811.3 | Last Updated 21 Sep 2014
Article Copyright 2010 by slelong
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid