Anda di halaman 1dari 10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

12,161,991 members 65,137 online

articles

Q&A

forums

Sign in

lounge

Searchforarticles,questions,tips

A USB Library to Detect USB Devices


slelong, 21 Sep 2014

CPOL

Rate this:

4.89 90 votes
A USB library to detect USB devices, and manage Attach and Detach events

Download demo 245.7 KB


Download source 20.7 KB

http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

1/10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

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:
Hide Copy Code

usingUSBClassLibrary;
Declare an instance of USBClass.
Hide Copy Code

privateUSBClassLibrary.USBClassUSBPort;
http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

2/10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

Declare an instance List<T> of DeviceProperties if you want to read the properties of your devices.
Hide Copy Code

privateList<USBClassLibrary.USBClass.DeviceProperties>ListOfUSBDeviceProperties;
Create an instance of the USBClass class.
Hide Copy Code

USBPort=newUSBClass();
Create an instance List<T> of DeviceProperties class.
Hide Copy Code

ListOfUSBDeviceProperties=newList<USBClassLibrary.USBClass.DeviceProperties>();
Add handlers for the events exposed by the USBClass class.
Hide Copy Code

USBPort.USBDeviceAttached+=newUSBClass.USBDeviceEventHandler(USBPort_USBDeviceAttached);
USBPort.USBDeviceRemoved+=newUSBClass.USBDeviceEventHandler(USBPort_USBDeviceRemoved);
Register your form to receive Windows messages when devices are added or removed.
Hide Copy Code

USBPort.RegisterForDeviceChange(true,this.Handle);
Then, check if your device is not already connected:
Hide Copy Code

if(USBClass.GetUSBDevice(MyDeviceVID,MyDevicePID,
refListOfUSBDeviceProperties,false))
{
//MyDeviceisconnected
MyUSBDeviceConnected=true;
}
Implement Attach and Detach handlers:
Hide Copy Code

privatevoidUSBPort_USBDeviceAttached(objectsender,
USBClass.USBDeviceEventArgse)
{
if(!MyUSBDeviceConnected)
{
if(USBClass.GetUSBDevice(MyDeviceVID,MyDevicePID,
refListOfUSBDeviceProperties,false))
{
//MyDeviceisconnected
MyUSBDeviceConnected=true;
}
}
}
privatevoidUSBPort_USBDeviceRemoved(objectsender,
USBClass.USBDeviceEventArgse)
{
if(!USBClass.GetUSBDevice(MyDeviceVID,MyDevicePID,
refListOfUSBDeviceProperties,false))
{
//MyDeviceisremoved
MyUSBDeviceConnected=false;
}
}
Handle Windows message in your form to pass them to the USBClass class:
http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

3/10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

Hide Copy Code

protectedoverridevoidWndProc(refMessagem)
{
boolIsHandled=false;
USBPort.ProcessWindowsMessage(m.Msg,m.WParam,m.LParam,refIsHandled);
base.WndProc(refm);
}

WPF
Add a reference to your project.
Add theusingdirective in your code:
Hide Copy Code

usingUSBClassLibrary;
Declare an instance ofUSBClass.
Hide Copy Code

privateUSBClassLibrary.USBClassUSBPort;
Declare an instance List<T> of theDevicePropertiesclass if you want to read the properties of your devices.
Hide Copy Code

privateList<USBClassLibrary.USBClass.DeviceProperties>ListOfUSBDeviceProperties;
Create an instance of theUSBClassclass.
Hide Copy Code

USBPort=newUSBClass();
Create an instance List<T> of theDevicePropertiesclass.
Hide Copy Code

ListOfUSBDeviceProperties=newList<USBClassLibrary.USBClass.DeviceProperties>();
Add handlers for the events exposed by theUSBClassclass.
Hide Copy Code

USBPort.USBDeviceAttached+=newUSBClass.USBDeviceEventHandler(USBPort_USBDeviceAttached);
USBPort.USBDeviceRemoved+=newUSBClass.USBDeviceEventHandler(USBPort_USBDeviceRemoved);
Override OnSourceInitializedin 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
Hide Copy Code

protectedoverridevoidOnSourceInitialized(EventArgse)
{
base.OnSourceInitialized(e);
HwndSourcesource=PresentationSource.FromVisual(this)asHwndSource;
source.AddHook(WndProc);
//USBConnection
USBPort.RegisterForDeviceChange(true,source.Handle);
USBTryMyDeviceConnection();
MyUSBDeviceConnected=false;
}

http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

4/10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

Handle Windows message in your form to pass them to theUSBClassclass


Hide Copy Code

privateIntPtrWndProc(IntPtrhwnd,intmsg,IntPtrwParam,IntPtrlParam,refboolhandled)
{
USBPort.ProcessWindowsMessage(msg,wParam,lParam,refhandled);

returnIntPtr.Zero;
}
Then, check if your device is not already connected:
Hide Copy Code

if(USBClass.GetUSBDevice(MyDeviceVID,MyDevicePID,
refListOfUSBDeviceProperties,false))
{
//MyDeviceisconnected
MyUSBDeviceConnected=true;
}
Implement Attach and Detach handlers:
Hide Copy Code

privatevoidUSBPort_USBDeviceAttached(objectsender,
USBClass.USBDeviceEventArgse)
{
if(!MyUSBDeviceConnected)
{
if(USBClass.GetUSBDevice(MyDeviceVID,MyDevicePID,
refListOfUSBDeviceProperties,false))
{
//MyDeviceisconnected
MyUSBDeviceConnected=true;
}
}
}
privatevoidUSBPort_USBDeviceRemoved(objectsender,
USBClass.USBDeviceEventArgse)
{
if(!USBClass.GetUSBDevice(MyDeviceVID,MyDevicePID,
refListOfUSBDeviceProperties,false))
{
//MyDeviceisremoved
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:
Hide Copy Code

publicstaticboolGetUSBDevice(UInt32VID,UInt32PID,refList<deviceproperties>ListOfDP,bool
GetCOMPort,Nullable<uint32>MI=null)
Set its value to Truein your connection code and retrieve the COM Port from the DeviceProperties structure:
Hide Copy Code

if(USBClass.GetUSBDevice(MyDeviceVID,MyDevicePID,
refListOfUSBDeviceProperties,true))
http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

5/10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

{
StringCOMPort;
//MyDeviceisconnected
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:
Hide Copy Code

publicstructDeviceProperties
{
publicstringFriendlyName;
publicstringDeviceDescription;
publicstringDeviceType;
publicstringDeviceManufacturer;
publicstringDeviceClass;
publicstringDeviceLocation;
publicstringDevicePath;
publicstringDevicePhysicalObjectName;
publicstringCOMPort;
}
Update the GetUSBDevice function:
Hide Copy Code

publicstaticboolGetUSBDevice(UInt32VID,UInt32PID,refList<deviceproperties>ListOfDP,
boolGetCOMPort,Nullable<uint32>MI=null)
{
...
DP.DevicePhysicalObjectName=String.Empty;
if(Win32Wrapper.SetupDiGetDeviceRegistryProperty(h,refDevInfoData,
(UInt32)Win32Wrapper.SPDRP.SPDRP_PHYSICAL_DEVICE_OBJECT_NAME,
refRegType,intptrBuffer,BUFFER_SIZE,refRequiredSize))
{
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
http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

6/10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

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
Formsspecific 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
EMAIL

TWITTER

About the Author


slelongNo Biography provided
Other HP
France

You may also be interested in...


Detecting USB Modem Device
http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

Prototype to production with


7/10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

using C#

IMSL Numerical Libraries

Detecting USB Drive Removal


in a C# Program

The Past, Present, and Future of


IoT

A USB HID Component for C#

Make your website mobile


friendly using Bootstrap

Comments and Discussions

You must Sign In to use this message board.


Search Comments

Go
First Prev Next

FTDI .. not detected well


Member 10942404 16Mar16 16:45
NOT WORKING WELL WITH FTDI COM PORT
Member 10942404 16Mar16 15:38
dont work with VB.NET
buddhafragt 17Dec15 14:27
Disconnected!
pip010 24Sep15 2:16
Re: Disconnected!
Member 10301930

15Dec15 9:46

Re: Disconnected!
pip010 20Jan16 0:44
USBClassLibrary Device ID or Serial Number resubmitted
Member 11983109 21Sep15 3:39
Error Compiling
Member 11972365

9Sep15 14:36

http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

8/10

3/23/2016

AUSBLibrarytoDetectUSBDevicesCodeProject

events always fire twice


jvdub22 27May15 9:59
I am not found library USB
Member 2458467 19May15 21:31
i don't find usb library.csproj
Member 9841125 27Mar15 10:26
What reference do I add?
Member 11450766 16Feb15 5:14
I don't found the USBClassLibrary.dll file
Armando Flores 26Jan15 8:24
Re: I don't found the USBClassLibrary.dll file
Member 11025298 28Feb15 6:11
NuGet
Robin Jones

14Nov14 5:31

Re: NuGet
slelong 16Nov14 9:45
Re: NuGet
Robin Jones

16Nov14 11:04

Retargeting for x64 causes an exception with fix


Robin Jones 18Oct14 11:39
Re: Retargeting for x64 causes an exception with fix
slelong 18Oct14 22:27
Re: Retargeting for x64 causes an exception with fix
Robin Jones 14Nov14 5:24
Error while compiling
Member 10851866 8Oct14 2:14
Re: Error while compiling
slelong 8Oct14 4:00
Re: Error while compiling
Member 10851866 8Oct14 4:15
Re: Error while compiling
slelong 8Oct14 4:56
Re: Error while compiling
Member 10851866 8Oct14 8:21
Refresh
http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

1 2 3 4 5 6 7 8 Next
9/10

3/23/2016

General

AUSBLibrarytoDetectUSBDevicesCodeProject

News

Suggestion

Question

Bug

Answer

Joke

Praise

Rant

Admin

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160311.1 | Last Updated 21 Sep 2014

Select Language
Layout: fixed | fluid

http://www.codeproject.com/Articles/60579/AUSBLibrarytoDetectUSBDevices

Article Copyright 2010 by slelong


Everything else Copyright CodeProject, 19992016

10/10

Anda mungkin juga menyukai