Table of Contents
- The Human Interface Device Class
- The HID USB Device Interface
- How to Integrate the Library into a Visual Studio Project
- How the HID USB Library works internal
- Where can I get the HID USB Library
Motivation
We wanted to find a new solution to connect our Hardware to the PC via USB because the experience we made with FTDI Chips was not satisfying at all.
The USB controller of our choice was the Maxim MAX3420E that is connected to the microcontroller through a Serial Peripheral Interface (SPI).
The MAX3420E comes without any drivers or libraries you can use to “speak” with it.
This is the reason why I had to develop my own “driver”.
After a day of reading and googling I decided that the best an easiest way is to use the Human Interface Device Class (HID). The HID-Class is a generic device class which means that all devices in this class are supported by Microsoft Windows and there are already existing DLLs with functions that we can use.
The start point for the “driver” was an article I found in the Microsoft developer network: „Is That You? Writing Better Software for Cool USB Hardware” written by Scott Hanselman. (http://msdn.microsoft.com/coding4fun/someassemblyrequired/isthatyou/default.aspx). Scott’s software is based on the USBSharp Class.
Luckily the MAX3420E comes with a code sample that configures the controller as a Human Interface Device so we didn’t have much trouble to find out how to configure it as HID.
The Human Interface Device Class
As mentioned above the HID Class is a generic device class so the driver is integrated in the operating system which makes things easy. If a new HID device is plugged in there is no need of any driver installation. The functions to access and control a HID device are included in the Windows hid.dll which is located in the System32 folder.
If you do not know for sure if your device is a HID device you should have a look at this little application. It is a part of windows and you can run it with the start -> run “msinfo32.exe” command. Or under Windows Vista just press the Windows-Key Type msinfo32.exe and hit enter.
USB Specific Stuff
Identify your USB device
USB device are identified by their vendor and product id. Those IDs are consisting of a prefix (“vid_” for vendor id or “pid_” for product id) and a 4 digit HEX number. The MAX3420E for example has the vendor id vid_06ba and the product id pid_5346. Usually both values can be changed in the source code of the USB device (assumes that you have access to that code).
Package Size / Communication Speed
HID devices are communicating with the pc through so called hid reports. Those reports consist of 64 bytes of data. Each microsecond one report is send from pc to the USB device and vice versa. This means that theoretical a transfer rate of 64 Kbytes per second can be achieved.
The HID USB Driver Interface
The driver is written in C# and designed as a DLL, this has the benefit so it is very easy to integrate the drive into a new project. Just import the DLL or the project and you are finished.
I tried to keep the interface as simple as possible on the one hand and on the other hand to integrate as much functionality as possible.
At the moment it has the following functions:
USBInterface(String,String) constructor
This method initializes a new instance of the USBInterface class.
Parameters
vid
The vendor id of the USB device (e.g. vid_06ba)
pid
The product id of the USB device (e.g. pid_5346)
USBInterface(String) constructor
This method initializes a new instance of the USBInterface class.
Parameters
vid
The vendor id of the USB device (e.g. vid_06ba).
Connect() method
This method establishes a connection to the USB device. You can only establish a connection to a device if you have used the construct with vendor AND product id. Otherwise it will connect to a device which has the same vendor id is specified, this means if more than one device with these vendor id is plugged in, you can’t be determine to which one you will connect.
Returns
False if any error occurs
Disconnect() method
Disconnects the device
getDeviceList() method
Returns a list of devices with the vendor id (or vendor and product id) specified in the constructor. This function is needed if you want to know how many (and which) devices with the specified vendor id are plugged in.
Returns
String list with device paths
write(Byte[]) method
This method writes the specified bytes to the USB device. If the array length exceeds 64, the array while be divided into several arrays with each containing 64 bytes. The 0-63 byte of the array is sent first, then the 64-127 byte and so on.
Parameters
bytes
The bytes to send.
Returns
Returns true if all bytes have been written successfully
startRead() method
This method is used to activate the “reading-State”. If you execute this command a thread is started which listens to the USB device and waits for data.
stopRead() method
This method switches from “reading-State” into “idle-State”. By executing this command the read data thread is stopped and now data will be received.
enableUsbBufferEvent(EventHandler) method
By calling this method with an event handler (System.EventHandler) the add-event listener of the USB Buffer is enabled. Thus whenever a dataset is added to the buffer (and so received from the USB device) the event handler method will be called.
Parameters
eHandler
The event handler (System.EventHandler) method.
How to integrate the HID USB Library into a Visual Basic Project
There a two ways to integrate the HID USB Library into a Visual Studio project. One is to add the library project to your Visual Studio solution. The other way is to add a reference to the USBHIDDRIVER.dll in the visual basic project you want to use.
Add the library project to a Visual Studio 2005 solution
1. Open your Visual Studio solution. Go to “File > Add > Existing Project”

2. The following Dialog will open. Navigate to the USBHIDDRIVER.csproj and click open.
3. Right click on your Visual Studio project and click « Add Reference »

4. Select the „Projects“-tab. Then select the USBHIDDRIVER and click ok.
![]()
Add the USBHIDDRIVER.dll to a Visual Studio project
1. Right click on your Visual Studio project and click « Add Reference »

2. Select the „Browse”-tab. Then navigate to the USBHIDDRIVER.dll.dll and click ok.
![]()
Use the USBHIDDRIVER.dll with Visual Basic 6
The .Net runtime allows unmanaged COM aware clients (like Visual Basic 6 applications) to access .Net components through the COM interop and through the tools provided by the framework.
The USBHIDDRIVER.dll is a .NET assembly which can not be accessed by Visual Basic 6. Therefore we have to create a type library which can be used with Visual Basic 6. This can be done with the Tool RegAsm.exe that you will find in the directory of your .Net framework installation.
Create a .bat file in the directory of the USBHIDDRIVER.dll and write the following command into it. Then run the bat file.
“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe” USBHIDDRIVER.dll.dll /tlb: USBHIDDRIVER.dll.tlb
Now you have to copy both the dll and the tlb file in the same directory as the application which is consuming it.
How to use the HID USB Library
Let’s say you want to communicate with an USB device that has the vendor id vid_06ba and multiple products id.
So the first thing you may want to have is a list of all devices connected to the pc which have the specified vendor id. To do this just make a new instance of the USBInterface class with only the vendor id as parameter. Then call the getDeviceList-Mehtod and you will receive a list of the devices that are connected.
USBHIDDRIVER.USBInterface usb = new USBInterface(”vid_06ba”);
String[] list = usbI.getDeviceList();
For communicating with the device make a new instance of the USBInterface class with the vector id and the product id as parameter. After that, you can call the connect-method and a connection will be established.
USBHIDDRIVER.USBInterface usb = new USBInterface(”vid_0b6a”, “pid_5346″);
usb.Connect();
Once your device is connected you can read or write data. To write data just call the write method with an array of bytes you want to send as parameter.
For reading you have to options: first without the USB buffer event and second with USB buffer event.
If the event is enabled, the event handler method will be called when a new dataset is received.
Otherwise you can process the data with a timer or something like this.
usb.write(startByte);
usb.enableUsbBufferEvent(new System.EventHandler(myEventCacher));
Thread.Sleep(5);
usb.startRead();
…
usb.stopRead();
usb.write(stopByte)
How the HID USB Library works internal
The library is based on the USBSharp class that imports all needed methods from the kernel32.dll and hid.dll. The HIDUSBDevice class wraps those methods and handles the read thread. The USBInterface is the main interface, which is accessible from outside the dll. In the USBInterface class exists a object of the ListWithEvent, which is basically a ArrayList with the bonus that an event is fired when a new dataset is added. Last but not least in the HidApiDeclaration class you will find some declarations needed for the whole hid-thing.
Where can I get the HID USB Library?
The project is hosted at http://code.google.com/p/csharp-usb-hid-driver/.
If you like the library and want to give something in return here is my Amazon Wishlist.







Were can I download this library?
Thanks!
Hi!
Where can I get this HID USB Driver?
Can you send it to me???
Thx and have a nice day! Dennis
Hi
you can download it here:
http://code.google.com/p/csharp-usb-hid-driver/downloads/list
How do I get the result of whatever is sent back from USB? I got the point of usb.read() its something like comm port get bytes, but how can I assing results to the variable?
The usb.read() function only starts the read process.
All data, which is read from USB is stored in usbBuffer (an ArrayList in the USBInterface Class).
<p>There is a working example in the project already (TestFixture.cs in TESTS folder).
All USB devices are identified by their USB vendor and product ID (In the example the vendor id is vid_0b6a, and the product id pid_0022).
If you have only one USB out for two sensors this question can only be answered by the specification / manual of your hardware.
Here is an example of how to read something USBHIDDRIVER.USBInterface usbI = new USBInterface(”vid_0b6a”, “pid_0022″)
usbI.Connect()
usbI.startRead()
Thread.Sleep(5)
for (int i = 0; i < 200; i++)
{
// DO SOMETHING WITH USBHIDDRIVER.USBInterface.usbBuffer HERE
Thread.Sleep(5)
}
usbI.stopRead()
I’m having a little problem with my USB device,
The problem is that i cannot access it via the value returned by “HidD_GetHidGuid” which is “{4D1E55B2-F16F-11CF-88CB-001111000030}”.
With this Guid I don’t see my device, BUT with “{A5DCBF10-6530-11D2-901F-00C04FB951ED}” this Guid YES!!.. My device is an USB TouchScreen. The other problem I have is that I want to read the data send by the Touch, this is for an app. I’m building where I have 2 monitors and with the Touch monitor can work with both monitors.
When I want to CreateFile with the 2nd Guid it returns -1 and also with this library cannot read the data.
Some help please!
Thanks a lot.
Guillermo.
Hi Guillermo,
please check if the operating system recognizes the touchscreen as keyboard or mice. If this is the case, the operation system will not allow you to access these device.
Regards,
Florian
I have a lot of entries sharing the same vid and pid - mainly come from some printer setup USBPrint, DOT4PRN, DOT4, DOT4…
I don’t know if this is the reason that the Connect() doesn’t succeed. I did supply the VID and PID in the constructor.
Any hint how to proceed? Too bad, Connect() doesn’t return any failure specific information for trouble shooting.
Thanks for your help.
Is the device you want to connect to a printer?
Because the library is only for human interface device class usb devices …
you are right I should implement some error information for trouble shooting
Yes, it is a printer.
I didn’t know that printer isn’t human interface device class usb devices.
so, does it mean I couldn’t use your library to connect to a printer? Too bad.
By the way, where can I find more information on USBSharp? Google doesn’t seem to provide me the original website of the library. Does the author of USBSharp remove his/her USBSharp from the net?
Thanks for your help.
I downloaded your library (uploaded to Google on Sept 19). It appears that the declaration for HidP_Value_Caps is missing the ULONG UnitsExp and ULONG Units fields defined in the Win32 HIDP_VALUE_CAPS structure.
Hello Kurt,
thanks a lot for your hint.
Does this have an effect on the functionality of the library? Because I can’t find one?
Okay, it looks like HidDeclarations.cs is basically unused so maybe that does not matter, but the HID structures are also defined in USBSharp.cs. In there the UnitsExp and Units fields of HIDP_VALUE_CAPS are defined, but their specified sizes appear incorrect as are LogicalMin/Max and PhysicalMin/Max which should all be 32-bit values. Do you concur?
Can you also explain your use of “unsafe” in declaring many of these structures that don’t appear to contain pointers? My understanding was that unsafe was only used with pointers.
This part is taken from the Scott’s Article so I don’t know much about it.
As you said the unsafe keyword is for pointers so maybe it is not necessary there.
I will rework the library as soon as I have some spare time. By the way everyone who wants to join the project is welcome
I’m be able to use synchronuos read mode (loop after startRead()) . I’d prefer use eventHandler mode but no events fire in my environment. Is there an example for this mode ? Test sample in package doesn’t seem use it (Handler is defined but loop is used).
Thank you for share this with us.
If you want to use the Event mode just add this:
usbI.enableUsbBufferEvent(newSystem.EventHandler(myEventCacher));
usbI.startRead();
Thank you Florian, EventHandler works now. I receive many notifications each command device for. I noticed this behaviour also with sample application included in Microsoft DDK. So I’ll have to filter only first notification and discard next (same) ones. Do you suggest to do un ArrayList.Clear() to usbBuffer or not ? It seems each notification append a new element on usbbuffer ArrayList (if I don’t clear() it)
Alberto, the event notifies you whenever a new data-set is added to the usbBuffer. If you clear the buffer after reading the content, you will have to ignore each second data-set.
I cant get any HID devices to show up with your tutorial. So i made a simple for loop to try all possible VID’s and still got nothing. Any help would be appreciated.
Dim usb As USBHIDDRIVER.USBInterface
Dim hexcount As String = “”
Dim vids As String = “”
Dim loopvar As Integer
For loopvar = 0 To 65535
If loopvar = 16 And loopvar = 256 And loopvar = 4096 Then hexcount = Hex(loopvar)
vids = “vid_” + hexcount
usb = New USBHIDDRIVER.USBInterface(vids)
Dim list As String() = usb.getDeviceList()
If list.Length 0 Then ListBox1.Items.Add(vids)
Next
Your library is great although having some trouble using it. I have been trying to write my own library and I was having some problem with that so I decide to try yours. I have created a C# application.
First I have a question. In your example code for connecting to a device,
USBHIDDRIVER.USBInterface usb = new USBInte..;
usb.Connect();
But from the code, the 1st line will create a connection a file (HIDHandle). Do we need the 2nd line?
The next question is the GUID. In the code you have
[assembly: Guid("3adea963-ff5f-4213-bc50-ac25c4769dfb")]
Is this the GUID of the software APP or the device? From what I can see, it seems to be the GUID for the APP. I ask because some of the other example code that I’ve seen uses specific GUID values, to what I thought was referencing the device, when calling SetupDiGetClassDevs & SetupDiEnumDeviceInterfaces.
Now to my problem. Basically I cannot seem to write to my USB device (SI Labs Eval board - which comes up as a USB-HID device). The return value for the WriteFile command always comes back as false (number of bytes written is 0) but when I check for errors (Marshal.GetLastWin32Error()), that is also returning 0. I’m struggling to come up with ideas as to why this is happening.
The code:
bool connected = false;
byte[] USB_iobuf = new byte[64];
USBHIDDRIVER.USBInterface usb = new USBHIDDRIVER.USBInterface(”vid_10c4″, “pid_8044″);
connected = usb.Connect();
USB_iobuf[0] = 1;
USB_iobuf[1] = 1;
// other USB_iobuf values are not included here
usb.write(USB_iobuf);
Any ideas?
Thanks in advance for any help!
Hi Florian,
first of all thank you very much for sharing this with us!
I experience quite the same problem as Thomas. The write() method always returns false…
Any lead ?
Many thanks. Cheers
Flo.
Hi guys,
sorry for the delay.
———-
@Jon:
If you run
USBHIDDRIVER.USBInterface usbI = new USBInterface(”_”);
String[] list = usbI.getDeviceList();
You will get all USB Devices plugged in.
———-
@ Anish Thomas:
Connect():
You are right, the usb[...].Connect() command is not needed to establish the connect. But it is usefull if the connection to device is lost and you want to re-establish it.
GUID:
It’s the GUID of the app.
@ Anish Thomas & Flo:
Write:
Are your shure that your device is accepting write requests and it is ready to receive?
A good way to debug the read and write function is using a USB Monitor (e.g. http://www.hhdsoftware.com/Downloads/usb-monitor.html)
If this does not help feel free to contact me
Hi Florian,
I’m trying to use the buffer event to read data, but my program just keeps locking up.
After I use Connect() I then do…
usb.enableUsbBufferEvent(new System.EventHandler(this.usbRecievedData));
usb.startRead();
And then I have a handler later in my code like this…
public void usbRecievedData(object sender, System.EventArgs e){
Debug.WriteLine(”received…”);
}
I’m expecting this handler to be triggered when data comes from my HID device, but nothing happen when no data comes from the device.
But my C# program is justing locking up, like it is stuck is some recursive loop.
Sorry, if I’m being stupid. I’m not experienced with C#.
Hope you can help! Thanks Tom
Hi there,
I am looking for a driver to intercept the USB-Keyboard in a way that Windows (XP/Vista) will not recieve the keys pressed - but it should only be recieved by the driver. (Multible keyboards on 1 computer)
Will i be able to use this driver for this?
Did anyone make a small examble application for using this driver?
/Kind regard,
Brian
Hi there,
I am looking for a USB driver to intercept USB-keyboards in a way that I can read the keyboard input but without having windows(Xp/Vista) direct the typings to any focused textboxes/controls.
Will I be able to use this driver for this purpose? Or will the input still be passed to window’s keyboard queue?
Did anyone make an example application in C# ?
/Brian
Hallo Florian,
Erst mal danke an Dich für diese Super-Package!
Ich hab ein Problem mit dem Buffer….
Sorry ich programmiere VB und bin in C’ noch nicht so bewandert. Ich habe eine A/D Wandlerkarte bekommen mit folgender Beschreibung:
Framegröße 64Byte, 8Byte Overhead
Offset Funktion Beschreibung
0×00 LENGTH Anzahl der Daten
0×01 BOARDTEMPL Boardtemperatur
0×02 BOARDTEMPH
0×03 PACKETNUMER Paketzähler 8Bit
0×04 COMMAND Befehl
0×05 ungenutzt ungenutzt
0×06 DATA Daten 56Bytes
-
-
0×3E ChecksumL 16Bit Prüfsumme(als 2er Komplement gespeichert)
0×3F ChecksumH
so und jetzt meine Frage …. Wie kann ich in VB den Buffer setzen? Kannst Du mir eventuell helfen ? Würde mich riesig über eine Antwort freuen!
Danke Dir im Voraus und wünsche Dir noch einen schönen abend!
Gruß Sven
Hi Brian,
the problem with keyboard and mouse is that windows will not allow to connect to them. So it will not work with this library. This library only works with such devices that are human interfaces devices but not a mouse or a keyboard.
Regards,
Florian
Hallo Sven,
also der Buffer ist ein Array du machst folgendes:
buffer[0] = 0×00 LENGTH Anzahl der Daten
buffer[1] = 0×01 BOARDTEMPL Boardtemperatur
usb.write(buffer);
Wenn es nicht gehen sollte einfach nochmal melden.
Gruß
Florian
Hi Florian!
I’m trying to get this running on a Vista laptop and a Metrologic 7120 USB barcode scanner.
I am able to find the device and call connect which is successful (it says), but when I do a startRead, nothing happens.
digging deeper, CT_CreateFile always seems to return 0 and (myUSB.CT_HidD_GetPreparsedData(myUSB.HidHandle, ref myPtrToPreparsedData) != 0) never is true and so never enters the read phase.
Any ideas, clues, directions???
Thanks in advance,
tim
i’ll try it soon.
nice tutorial.
thank you.
suriva
Hi Tim
sorry for the delay …
is this barcode scanner recognized by Windows as keyboard? Because Windows will not allow for connecting with the HID library if the device was recognized either as keyboard or as mouse.
Regards,
Florian
hi, Florian Leitner.
I’m a student of electrical engineering in indonesia. several month ago i tried to learn USB and make ‘max3420′ works. and last week it’s happen like maxim tutorial. and after that,i’m going to start my final project to make some application that using usb connectivity.and the problem is, i still can’t reply host ‘out’.i don’t have much information to developed it.
can you explain how you configure the ‘max3420′ in your tutorial? did you use another endpoint? (in maxim tutorial-HID, just endpoint in 3 interrupt)
how device send data if endpoint out 1 is not configured? any changes in report descriptor?
can you send me your example code that i can learn?
sorry for my english. i’m still learning.i hope you will understand my message.
thank you for your help.
suriva
Hi,
i have a little strange problem.
I am using VB.NET;
If i use event handler i don’t receive the event..i have to use startread() to receive the event.
And I can’t use Write(), i have to use stopread into the event Sub. It doesn’t work in another part of the program…why? can i fix this problem?
Anybody can tell me what output report used for?can HOST send data to device if device was configured as HID?how it can?and what specific data that HOST can send to device?
It’s amazing
hi,
help please.
i have aproblem with write to the usb.
the connect is successful ( i got “true” from the function) but the function UsbI.write() all the time return “false”.
i am using also USB Monitor Pro and i see that there is no writing to the device.
when i debug the software i see that the failure happens in the low level function USBSharp.WriteFile() in HIDUSBDevice.cs file this function return “false”.
my device is microcontroller ARM with a firmware that supports USB HID.this device works good for writing and reading with other HID Software so i dont think that the problem is in the device .
is everyone have any idea what is the problem?
thanks
lior
p.s
Hi !
I have the same problem as another post. The Guid returned by HidD_GetHidGuid is wrong. but in my case it works with another Guid : ‘3abf6f2d-71c4-462a-8a92-1e6861e6af27′. This is very weird i must say ! I’m not trying to get a specific device, i just want to enumerate all with a call to this :
IntPtr pointer = SetupDiGetClassDevs(ref id, 0, IntPtr.Zero, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
Any reason why this happens?
thanks
Hallo,
wie kann man die DLL ein Delphi verwenden? Das Problem ist das Erstellen der Klasse selbst, denn würde die DLL nur einfache Funktionen enthalten, könnte ich die via GetProcAdress ansprechen.
Gruß, Carsten
Hi, i would like to know how i can use USBHIDDRIVER to find the vid and he pid of all the HID that i have pluging in my pc.
Hallo Carsten,
ich kenne mich mit Delphi leider zu wenig aus um Deine Frage beantworten zu können.
Schau doch mal hier: http://www.delphibasics.co.uk/Net.html
Miguel,
you can try something like getDeviceList(”").
You’ll get a StringList of all USB devices.
Regards,
Florian
Hi,
I just added some code to solve a small bug in your program. Inside HIDUSBDevice.cs –> readData() –> after:
else if (dataReadingThread.ThreadState.ToString() == “Running”)… etc
I added:
else if (dataReadingThread.ThreadState.ToString() == “WaitSleepJoin”)
{
//Stop the Thread
dataReadingThread.Abort();
}
this to make sure that the thread can be stopped although no data is recieved by the USB device. If I don’t use this extra code then the driver starts again another thread…..
Best,
Sven
Hi Florian,
I’m very happy finding your library, it would make my life 100 times more easier with 1 restriction
I can’t find out, why can I only “talk” with HID devices?
In my case, I have a Non-fiscal thermo-printer (Wincor Nixdorf TH230) wich is connected a powered-usb (24V) and i can find it on the device list PID and VID too but i cannot retrive the serial number because it’s not known as a HID device by Windows (Windows Embedded for POS).
Do you have any ideas how can i bring this to run?
Mfg
Laszlo
Hi,
ich habe das selbe Problem wie lior.
beim connect gibt es ein true zurück doch beim write ein False.
kann es evt. daran leigen das es unter der pid bei
“String[] list = usbI.getDeviceList();”
drei Einträge gibt mit der gleichen vid und pid
jeweils durch &mi_10X und &col0X
unterschieden.
Kann es damit zu tun haben?!
das gerät wird erkannt.
sowhl die integrierte Maus als auch die Tastenw erden erkannt.
Mit freundlichem Gruß
Patric Karwat
Hi Patric,
if your HID is recognized by the OS as keyboard or mouse it will not allow you to write to this device.
You have to change the device type in the firmware of your device.
Regards,
Florian
ok ich noch mal,
es sind drei Geräte beim reinstecken initialisiert:
maus, Tastatur UND
eine HID-Conformes Gerät
an denen ich z.B die LEDs ansteuern kann.
das geht weiß ich, da ich es mit einem Tool testen konnte.
Patric
Hallo Patric,
ok, es wäre sehr seltsame wenn alle drei Geräte die selbe vid und pid hätten (zumindest bei der Maus und Tastatur kann dies eigentlich nicht sein).
Mit welchem Tool hast du es den getestet?
Gruß
Florian
Hi I am working with a Logitech Extreme 3D joy stick. As I move pitch (or roll)it goes 0-255 several times as if there is another number/factor I need to catch. It does not show up in the array.
Thanks.
I just received this eMail from Greg:
Just a follow up. I got the joy stick where pitch and roll was divided into 4 segments of 255 to work very well. I just set the program to recognize when it went from say anything above 200 to anything bellow 50 to add 255. Now the joy stick reads 0 to 1020 and it does it well.
Sorry Florian, I wrote this question after. That worked great for roll which was divided into 4 groups of 255 but then I found out pitch was divided into something like 14 groups of 255. It is jumping too far to predict the segment unless I am moving real slow my identifier starts migrating.
Has to be some other identifier.
Thank you sir, Great driver!!!
The numbers are embedded in the other numbers. Sorry to have side tracked you here.
Thanks
Hi Florian,
Many thanks for this really useful library.
I’ve been having some problems getting it to find HID devices.
I try:
USBHIDDRIVER.USBInterface usbI = new USBInterface(”_”);
String[] list = usbI.getDeviceList();
Console.WriteLine(list);
while (1 == 1)
{
Console.Write(list[0]);
}
Which results in an array index out of range error. I’m trying to get it to send an HID_REQ_GET_REPORT message eventually, but I can’t get it to find anything.
Also, my apologies for the infinite loop.
Hi florian,
I just added the library, but it still show “Device Not Found”. What’s the problem with it?
Any led?
thanks so much.
(Fortsetzung von Post 48)
Hallo Florian,
durch meinen Urlaub konnte ich mich leider nicht mehr melden. Also greife ich das Problem noch einmal auf.
Ich habe hier mal die ausgabe der Funktion:
getDeviceList() aus:
[0] = “\\\\?\\hid#vid_f6ff&pid_0800&mi_00&col01#7&139a975d&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}”
[1] = “\\\\?\\hid#vid_f6ff&pid_0800&mi_00&col02#7&139a975d&0&0001#{4d1e55b2-f16f-11cf-88cb-001111000030}”
[2] = “\\\\?\\hid#vid_f6ff&pid_0800&mi_01#7&26cab39b&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}”
ich denke mal (ich habe da Projekt so übernommen und muss darauf vertrauen das es die richtige vendorID ist) dass das die drei geräte sind die angeschlossen worden sind:
Maus tastatur und eben das eingabe HID.
kann man das HID nun unabhänig ansteuern?!
Mit freundlichem Gruß
Patric Karwat
Hi Florian
I am using VB6 and have generated tlb as per instructions, put in in the App Directory and have a reference to it.
If I put Dim usb As USBHIDDRIVER.USBInterface then I get Compile Error User-defined type not defined.
Please could you tell me where I am going wrong?
Thanks
Andy.
Hi Florian,
Impressive work. Thanks.
I’m using MS C# 2005. Simple code:
usb = new USBInterface(”vid_0801″, “pid_0002″); //Magnetic stripe reader
usb.enableUsbBufferEvent(new EventHandler(myEventCatcher));
usb.startRead();
It works nicely, but when I close the window, the task remains there, as if there was a thread still running.
I’ve tried to use stopRead() before closing, but that doesn’t help either.
Maybe you can help me?
Thanks
One more thing:
What if we use several Hid devices?
I’ve noticed that your Test sample code grabs info from the
I use this:
private void myEventCatcher(object sender, EventArgs args) {
USBHIDDRIVER.List.ListWithEvent list = (USBHIDDRIVER.List.ListWithEvent)sender;
Byte[] b = (Byte[])list[0];
for (int i = 0; i
Sorry, my last post was truncated for some reason.
Nevertheless, I can indeed read from 2 devices. No problem.
The problem that remains though is that after closing the app, it seems as if a thread is still running, because the app is still alive somehow. Perhaps the associated EventCatcher is still running?
BTW, the devices I’m reading from are 2 magnetic swipe readers: Magtek and IDTech. When I use win32 (using Delphi), I need to use Report Descriptors, which is a very different way of getting info from the device.
I know you’re doing this for free, but we’re willing to pay for your time.
Hey, there are good deeds and there is a need to make money as well, and they don’t contradict each other.
If you please could let me know how much you charge by the hour, I’ll appreciate it.
Dear Florian,
Is it possible to capture with your SDK two HID keyboard mode barcode scanners data before it enters into the keyboard buffer? We like to crank up something that supports multiple HID keyboard barcode scanners but right now the data is mingled together. Do you have a solution for that?
Kind Regards, GZ
Works like a charm!
Thanks
I can’t put this to work.. what I’m doing wrong?
Here is my code:
————————————————
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
USBHIDDRIVER.USBInterface usb = new USBHIDDRIVER.USBInterface(”vid_040b”, “pid_6510″);
usb.Connect();
usb.enableUsbBufferEvent(new System.EventHandler(myEventCacher));
Thread.Sleep(5);
usb.startRead();
for (int i = 0; i
I trying to read (without success) from a USB codebar scanner.
Windows identify my codebar scanner as a ‘HID Keyboard Device’.
My vid and pid are ok!
Can I read from this?
Thanks for posting this. Its alot simpler to use than other drivers I’ve seen out there. But I’m having a similar problem.
If USB.Connect() Then
USB.enableUsbBufferEvent(New EventHandler(AddressOf Me.DataIncoming))
USB.startRead()
……
Public Sub DataIncoming(ByVal sender As System.Object, ByVal e As System.EventArgs)
MsgBox(”Data Received”)
The DataIncoming event does not fire when I swipe a card through my card reader. Is there something I’m missing
I figured it out on my own. In order for this code to work, it has to be a true HID device. It can not be a keyboard device. The device that I have allows me to configure it as either keyboard or true HID. Once I switched it to true HID my event started to fire.
This currently (09-2007 release) doesn’t work correctly with 64-bit Vista in Visual Studio 2008 if you compile for “Any CPU”. I wasn’t getting back any devices. Switching to “x86″ gives me back data. I guess I’ll need to look at the code to see if there are any data sizes with incorrect data types (32 vs 64 bit).
Tomi, do you happen to have a VS 2008 C# example I can get a copy? Or can you past the code in here least? Thanks in advance.
Great Job! Thanks! I was looking for a driver like yours and you saved me a lot of work. Couple of comments though:
1. Compiling the USBHIDDRIVER under VS2009 with SP1 generate the following warning:
‘USBHIDDRIVER.USB.HIDUSBDevice.usbThread’ is never assigned to, and will always have its default value null”
Indeed the usbThread is declared in the class HIDUSBDevice as private and the only reference to it is to Abort this thread in the method: disconnectDevice() in the same class.
There are several other inconsequential warning for other vars declared but not used but the reference to the thread worries me.
2. I am attaching a simple C# application that I used to test the driver. (John is this what are you looking for?)
This code opens a HID device (PowerMate button from Griffin), and then sets itself to to receive packets from the device. It uses a delegate to display the data in a list. I used your Test methods and everything works great with the following exception:
If I Connect to the device, set to receive and then disconnect the driver goes non responsive after attempting to return in CT_CloseHandle() in the USBSharp class.
If just open and then close the connection, without an attempt to receive, there is no problem.
Any suggestion? By the way I am using Vista Ultimate 32 bit with the latest drivers from Griffin.
Send me an e-mail for the entire project…
Aurel
================================
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using USBHIDDRIVER;
namespace HIDTest
{
public delegate void DisplayUSBDel( String val );
public partial class Form1 : Form
{
USBHIDDRIVER.USBInterface usbI = new USBInterface(”vid_077d”, “pid_0410″);
private String[] listOfDevices;
private String hexOutput = null;
private Boolean connectFlag = false;
private Boolean receiveFlag = false;
public Form1()
{
InitializeComponent();
}
private void DeviceList_Click(object sender, EventArgs e)
{
USBHIDDRIVER.USBInterface usbI = new USBInterface(”0″);
listOfDevices = usbI.getDeviceList();
for(int i=0; i 0)
{
byte[] currentRecord = null;
int counter = 0;
while((byte[])USBHIDDRIVER.USBInterface.usbBuffer[counter] == null)
{
//Remove this report from list
lock(USBHIDDRIVER.USBInterface.usbBuffer.SyncRoot)
{
USBHIDDRIVER.USBInterface.usbBuffer.RemoveAt(0);
}
}
//since the remove statement at the end of the loop take the first element
currentRecord = (byte[])USBHIDDRIVER.USBInterface.usbBuffer[0];
lock(USBHIDDRIVER.USBInterface.usbBuffer.SyncRoot)
{
USBHIDDRIVER.USBInterface.usbBuffer.RemoveAt(0);
}
//DO SOMETHING WITH THE RECORD HERE
//
hexOutput = Convert2HStr( currentRecord, (short)currentRecord.Length);
DisplayUSBDel d = new DisplayUSBDel(ShowUSBData);
Invoke(d, new object[] { hexOutput });
}
}
private string
Convert2HStr( byte[] sBin,
short sNo )
{
short i;
short j = 0;
String dStr = null;
for( i = 0 ; i < sNo ; i++, j++ )
{
dStr += String.Format( “{0:X2} “, sBin[ i ] );
}
return dStr;
}
}
}
Hi, Aurel I’m trying to implement this USBInterface class with a simple form example like yours, but I’m having problems with how and what to send to usb, could you send me the complete project to take a complete look? would be great!!
Thanks in advance!
Hi I was wondering if you could give me a hand using this class. I can get the list of Device and I have passed the Vid and PID and can read and from device but. I was wondering how I can use the data to grab the Red Button key press on a MCE RC6 Remote. I am currently using the EnableUsbBufferEvent(EventHandler) method but the byte record return is always the same for each key press (Diff Keys) on the remote. I was wondering if you point me in direction of reading these individuals Values:
private void dothis(object sender, EventArgs e)
{
if (USBInterface.usbBuffer.Count > 0)
{
byte[] CurrentRec = null;
int count = 0;
USBHIDDRIVER.List.ListWithEvent list = (USBHIDDRIVER.List.ListWithEvent)sender;
Byte[] b = (Byte[])list[0];
MessageBox.Show(b[0].ToString() + b[1].ToString());
CurrentRec = byte[])USBInterface.usbBuffer[0];
foreach (byte str in CurrentRec)
{
Recs += “\n” + str.ToString();
//MessageBox.Show(CurrentRec[0].ToString()+str);
// MessageBox.Show(str.ToString()+” : ” +Recs);
}
//lock (USBHIDDRIVER.USBInterface.usbBuffer.SyncRoot)
// {
// USBHIDDRIVER.USBInterface.usbBuffer.RemoveAt(0);
// }
// }
// listBox2.Items.Add(Recs);
}
// USBHIDDRIVER.USB.USBSharp UsbSharp = new USBHIDDRIVER.USB.USBSharp(USBInterface(”vid_” + textBox1.Text, “pid_” + textBox2.Text));
// MessageBox.Show(UsbSharp.DevicePathName+” “+UsbSharp.HidHandle);
}
Hi bernardo,
my e-mail is aureel@mitem.com. Send me your e-mail and I will mail you the project
Aurel
opps, my e-mail is aurel@mitem.com
Hi aurel, my e-mail is bermtz@gmail.com
thanks for the quick reply
hi,
help please.
i have aproblem with write to my usb device.
the connect is successful ( i got “true” from the connect() function) but the function Usb.write() all the time return “false”.
i am using also USB Monitor Pro and i see that there is no writing to the device.
when i debug the software i see that the failure happens in the low level function USBSharp.WriteFile() in HIDUSBDevice.cs file this function return “false”.
my device is microcontroller PIC 18f4550 with a firmware that supports USB HID.this device works good for writing and reading with other HID Software so i dont think that the problem is in the device .
is everyone have any idea what is the problem?
thanks
valioman
Does anyone have a version that is compatible with both 32 and 64 bit os?
how to communicate usb device in c#
Hi all
Help me please
I want to add the USBHIDDRIVER.dll file to my poject,, Where can I must access this dll file?
is it beside the project or it is a COM .NET framework dll that I must add it. If it is beside the project plz send the dll for me to my email :
a_amini313@yahoo.com
Hi Florian
I understand that your nice code cannot work on devices that are recognized by Windows as mice or keyboards. Do you have any advice for how to read those devices out?
I would like to add 2 more optical mice to my PC and read their output in real time in my application, without them being recognized as mice (ie without them moving the cursor, etc). Any advice would be greatly appreciated.
Many thanks
-Matt
Hi;
Can I intercept the data between an application and a USB device using this DLL?
Hi iMan,
if you need this merely for debugging purpose, I would recommend to use the HHD USB Monitor http://www.hhdsoftware.com/Products/home/usb-monitor.html.
Best regards,
Florian
Florian,
When you connect the MAX3420E and make CONNECT bit 1. Does the MAX send its vendor id and device id? or should you do the work?
Hi,
I have designed my activeX control with the win32 usb library. all work fine and i am getting the detection as well as the event notification into my web application throught javascript.
The only problem is when i close my HTML page this make the device disconnected.
I am using the win32.unregister “Win32Usb.UnregisterForUsbEvents(Handle)” alos on my usercontrol dispose method on the activex side. but that dosen’t makes any changes.
Please help me as t his is kind of a urgent thing
Thanks & Regards
Syed
[...]
Hi Florian
I’m connecting my usbhid device but Im not writing data mydevice.other hid software writing mydevice.when writing mydevice function always returned false.I’m not understand. please help me
Hi, Florian
I’m trying to connect mouse and keyboard but it isn’t working for these HIDs. I providing the exact vid and pid in Interface Constructor and when trying to call Connect() it returns ‘false’.
Please reply.
Hi M. Ilyas,
unfortunately the access to keyboard / mouse is blocked by the operating system.
Regards,
Florian
Dear Florian,
Your library has been of immense help to me, and i’ve been able to recognize my device with it.
However, i have still not been able to read data from my device.
i have used the following commands:
usbI.enableUsbBufferEvent(newSystem.EventHandler(myEventCacher));
usbI.startRead();
but when i debug my code it returns an error.
I have also used a code in which i have executed this loop.
usbI.Connect()
usbI.startRead()
Thread.Sleep(5)
for (int i = 0; i < 200; i++)
{
// DO SOMETHING WITH USBHIDDRIVER.USBInterface.usbBuffer HERE
Thread.Sleep(5)
}
usbI.stopRead()
in this case, there are no errors, but the buffer appears to remain empty.
Please help me out,
Regards,
Faizan
Hi Faizan,
what error message is returned by the debugger?
You can use http://www.hhdsoftware.com/Downloads/usb-monitor-lite.html to check if your device is actually sending some data.
What kind of device do you use?
Regards,
Florian
thanks for your time.
i am using cypress usb development board. the number of devices and their paths are shown correctly. but i am facing problem with READing data from the device. when i put some data in the usb buffer and then read. it works and the correct data is given. but i cant find any data coming into yhe buffer from the device.
and the following error i get when i use the event handler method
“Error 2 The name ‘myEventCacher’ does not exist in the current context C:\Documents and Settings\faizan.rasool\My Documents\Visual Studio 2005\Projects\edited\edited\Form1.cs 53″
regards
Faizan R
Dear Florian
the error problem is solved now but still i cant get any data from the device.
please help me out.
regards
Faizan R
Dear Faizan,
have you checked with the HHD USB Monitor (http://www.hhdsoftware.com/Downloads/usb-monitor-lite.html) if your device is actually sending data?
Is it possible that your device is recognized as keyboard or mouse?
Regards
Florian
Dear Florian
After connecting the device, i checked in the device manager whether the device was being detected as a mouse. But it wasnt. The computer simply detects It as an HID device.
The USB monitor detects the device and also the data that we send through it.
Regards,
Faizan
Hi, Florian,
It should be a great piece of library. Thank you.
I am using Visual Studio 2008 writing in C++. How should I include your .dll into my project? There seems no header file to include.
Thanks,
Scu R.
Hi Scu R.,
have a look at http://blogs.msdn.com/jigarme/archive/2008/04/28/com-interop-sample-using-c-dll-from-c-application.aspx
If the example doesn’t answer your question feel free get back to me.
Regards
Florian
Hi Florian,
Thanks for your reply. I have tried a few examples of calling C# dll from C++. I can do that for those simple examples, when there is only one class in the dll.
But for your C# library, I have encountered a major problem. I modified interface.cs to
”
namespace USBHIDDRIVER
{
///
/// Interface for the HID USB Driver.
///
[ComVisible(true)]
[Guid("C57FFE4C-B2D8-4ba5-B699-A53F3D1CEBC1")]
public interface IMyDotNetInterface
{
bool Connect();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("5FDE6798-7531-4f8b-A609-51DB2FD21DFF")]
[ComVisible(true)]
public class USBInterface:IMyDotNetInterface
{
……
”
And AssemblyInfo.cs to
”
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("USBHIDDRIVER.Properties")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("USBHIDDRIVER.Properties")]
[assembly: AssemblyCopyright("Copyright © 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(true)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("94F59581-09C7-4c52-AE3F-936302ABE070")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyKeyFile("C:\\Users\\User1\\Desktop\\Downloaded Source Code\\csharp-usb-hid-driver\\USBHIDDRIVER\\bin\\Release\\TestKeyPair.snk")]
”
However, after I registered the DLL file using regAsm ( C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe USBHIDDRIVER.dll /tlb:com.USBHIDDRIVER.tlb /codebase), I used the old OLE/COM viewer and it showed that there are ONLY three classes listed in “All Objects”:
ListWithEvent (under USBHIDDRIVER.List)
USBTestFixture (under USBHIDDRIVER.TESTS)
USBSharp (under USBHIDDRIVER.USB)
But not my intented “USBInterface” class.
My C++ client program shows “Class Not Registered” error.
The client code is:
”
#include”stdafx.h”
#import “C:\Users\User1\Desktop\Downloaded Source Code\csharp-usb-hid-driver\USBHIDDRIVER\bin\Release\com.USBHIDDRIVER.tlb” raw_interfaces_only
using namespace USBHIDDRIVER;
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = CoInitialize(NULL);
IMyDotNetInterfacePtr pIUSBHIDDRIVER(__uuidof(USBInterface)); <– Here is the unregistered error coming from
CoUninitialize();
return 0;
}
Has your C# DLL been using in C++ applications? How is it done?
Many thanks,
Scu R.
It is very useful !
thanks for sharing.
Dear Florian,
Thanks for all the help with HID. I tried your sample and connected to my Device with no problem. I do however have no idea how to send any data to a from the HID device. Do you have any sample’s to send command to the HID device.
Thanks again for the great tips
Regards
Ian
Really good c# lib for usb!
Works with Windows 7 great so far, played with:
-> USBInterface.usb.Connect()
-> USBInterface.Disconnect();
-> USBInterface.startRead();
-> USBInterface.enableUsbBufferEvent();
64 bit problem can be fixed as so: (requested above)
http://www.codeproject.com/KB/cs/USB_HID.aspx:
myPSP_DEVICE_INTERFACE_DETAIL_DATA.cbSize =
IntPtr.Size * 8; == 64 ? 8 : 5;
[StructLayout(LayoutKind.Sequential, Pack = 1)]
protected struct DeviceInterfaceData
{
public int Size;
public Guid InterfaceClassGuid;
public int Flags;
public IntPtr Reserved;
}
A visual C++ version would be great please as i’m writing a foot pedal driver…
Thanks again!
Great library, Florian! A big help for my project. (I’ll have to check that wishlist!)
However, I don’t understand the usefulness of the List.ListWithEvent. At first I thought it might clue me into when a USB device was plugged or unplugged. But that doesn’t seem to fire.
Maybe I’m not doing it correctly (I’m not all the great a programmer, anyway).
Can anyone suggest what the ListWithEvent is useful for? Or better, yet, how I can detect, using this library, that the magstripe reader has been unplugged or plugged back in?
Thanks in advance.
Bill,
thanks!
The ListWithEvent fires a event as soon as a new packet from the usb device is received.
One way to detect if the magstripe reader is connect or not is to call getDeviceList() periodically and scan the list that is returned.
(This way is not very elegant but it works)
Best regards,
Florian
How do I use your read functions? I mean there’s nothing, as far as I can see, on how to pass an input buffer so that in blocking calls (without registering a buffer event handler)
Hey Florian:
I came across this the other day, and for some reason (and for the life of me) I can’t get this to connect to a device. I am CERTAIN I have the various ID’s correct (vendor 0×1DD2, product 0×102, version 0×16 FWIW). Yet no matter what me checking for a connection is false, and as a result I can’t write to the device. Do you have any idea’s for me?
Thanks,
Dustin
Dustin,
what kind of device do you use?
Regards,
Florian
I use a LED Cluster/Joystick combo (SLI-M… http://www.leobodnar.com) . I can verify that it does work as there are various test applications from the device manufacturer himself and also just generic HID test applications. It’s very strange that I don’t get any connection though, even if I make the vendor/product 4 characters.
Hi Dustin,
sorry but without having access to the hardware, I can not imagine what could be wrong …
Regards,
Florian
It’s strange, especially as it’s not unique to your library. However, it only happens to applications that I compile myself whereas test applications by other people work perfect. Is there any special dependencies or special things I need to put into my C# application?
An Update:
I’ve found the solution. Compiling both the Library and the application that is being created as a 32 bit (forced in Project settings) solves the issues I was running into.
Thanks,
Dustin
Hi, i have been searching about HID USB libreries for a week because i have a special joystick which need to receive a Set_Feature 1 before start to send packets. I tried a lot of things and all crash or dont compile or something similar.
Looking at the source code i saw you import the Set_Feature from hid.dll
Is this function avaiable throught VB6? Can you write a little example of how to use your lib with vb6? Im getting a lot of sintaxis errors >.<
I only need to connect to my joystick and send a feature report = 1
but im starting to think is imposible to write something for it easily, can you help me please?
if anybody have any problem with the connection first check the vid and pid string values. It worked for me after i changed the values from capital caracters.
Like this:
Not working: usb = new USBInterface(”vid_03FZ”, “pid_2013″);
working: usb = new USBInterface(”vid_03fz”, “pid_2013″);
Hi Florian,
first of all: this is one great library. after spending days with the microsoft windows DDK, this is something is was looking for.
My Problem now is: an HID-compatible device (AVR-Controller) sends binary data over usb to the pc, whereas windows on the pc executes the recieved data as window messages(KeyCode, SystemEvent, etc.). Do you have a solution or an idea of howto terminate the parsing of such messages by the native wm_proc function under any windows application? After looking too long at the windows dde, i would prefer a managed code solution…
Nevertheless, thank you very much for developing and introducing this library.
best regards JKP
Hi,
I am trying to use your DLL in VB6. I followed your instructions to make the .tlb file successfully. I have the DLL and the tlb files together in a directory. VB6 accepts the reference toy the tlb file. But if I press F2 to bring up the object bowser the list contains only the entry USBHIDDRIVER and no ‘method’ or ‘events’ that I can use.
Am I doing something wrong?
I am trying to read a USB thermometer (temper)
In addition, the tlb file is empty
I must be doing something wrong in the conversion.
THe string to create the tlb file is
“C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe” USBHIDDRIVER.dll /tlb: USBHIDDRIVER.tlb
Hi
Is there any examples of your code in Visul basic 2005. I have tried to understand the csharpe but can’t get my head arround it. All i need is to achieve is when a card is swiped on a magtek card reader that a form pops up on the screen and passes the data to a text box. I am happy to buy 1 or 2 items in your whish list if you can help.
Thanks
I downloaded the zip file, now what do I do ? I have Visual Studio 2008 C# Express Edition but when I try to open the solution file, a “Conversion Wizzard pops up”. What I am doing wrong ?
The conversion wizard pops up, because project is a Visual Studio 2005 project, just go through the wizard and you’ll be fine.
@John: Unfortunately I have now Visual Basic 2005 sample code, but I’m pretty sure tat there should be some sample code, on how you can use code of a c# project in visual basic, available. Try google with visual basic com, or using c# in visual basic project.
Hi!
In the VS 2008 will be the project file not accepted. If i try to open it in the vs2008 open project browser, they will be not displayed. If i made simply doubleclick on it, only not usable html file, will be opened. But the menue: >Build>Rebuild>…>AddReference>… , will not be available. I try it on the german Microsoft Visual Basic Express edition 2008, and on the english full version too. The same thing. Is there a way to publish it on the 2008 version instead 2005 ?
Or a guide, how to open it in the 2008 version.
Next i try it to test under VB6, because the generatig of the files was ok, so i will see. Best regards, thank you,
Feri
(you can write on my email in german too)
I was able to reproduce the Problem you had with Visual Studio 2008.
Visual Studio 2008 was not able to open the Class Diagram file that was contained in the project.
I uploaded a new version, where the issue is resolved.
Hi!
What is the proper way to stop the reading thread?
I use the code below and everything works great except the fact, that when I close the form, application remains running.
Is there any solution for this?
private void TestButton_Click(object sender, EventArgs e)
{
this.usb = new USBInterface(”vid_047f”, “pid_4254″);
bool res = this.usb.Connect();
this.usb.enableUsbBufferEvent(new EventHandler(this.usbEventHandler));
this.usb.startRead();
}
private void usbEventHandler(object sender, EventArgs args)
{
ListWithEvent list = (ListWithEvent)sender;
byte[] byte_array = (byte[])list[list.Count-1];
Debug.WriteLine(”");
for (int i = 0; i < byte_array.Length; i++)
{
Debug.WriteLine(i + “: ” + byte_array[i]);
}
Debug.WriteLine(”");
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
this.usb.stopRead();
}
Hi Alex,
this should solve the problem: http://code.google.com/p/csharp-usb-hid-driver/issues/detail?id=1
Florian
how can I extract the data from the
.read()?
Using VB 2008
Hi Florian,
sorry for my bad english….
we have started a usb-based project and have take a look to your library.
Very soon we have had a “stop-reading” problem with a simple application.
Investigating we have solved (for us) the problem and I post here the modifications to your code (open source spirit) :
in the class HIDUSBDevice.cs :
public void readDataThread()
{
int receivedNull = 0;
while (getConnectionState()) // <—– modification
{
int myPtrToPreparsedData = -1;
if (myUSB.CT_HidD_GetPreparsedData(myUSB.HidHandle, ref myPtrToPreparsedData) != 0)
{
int code = myUSB.CT_HidP_GetCaps(myPtrToPreparsedData);
int reportLength = myUSB.myHIDP_CAPS.InputReportByteLength;
while (getConnectionState()) // 100)
{
receivedNull = 0;
Thread.Sleep(1);
}
receivedNull++;
}
}
}
}
}
public void disconnectDevice()
{
try {
if (usbThread != null) {
usbThread.Abort();
}
}
catch (Exception ex) {
Console.WriteLine(”HIDUSBDevice.disconnectDevice : ERROR aborting usbThread : ” + ex);
}
setConnectionState(false); // <——— modification
myUSB.CT_CloseHandle(myUSB.HidHandle);
}
With these modifications the calling code to stop reading from device looks like :
usbI.stopRead();
usbI.Disconnect();
usbI = null;
… Another consideration….
In writeData(byte[] bDataToWrite) you set the output report length at 64+1 bytes but this is not ever true, depends from usb hid device, for example our device has 32 bytes of report length. I not have tryed but this may be set at myUSB.myHIDP_CAPS.OutputReportByteLength+1, what do you think?
I hope this helps someone.
Germano.
I am using magtek usb device in a application. Can I use this dll to read the response message of magtek?
And what is way to using the dll. Can you help me?
Hi!
Is there someone, that can publish a little skeleton of VB6.0 and/or VB.net application? I cannot understand how to do simple read (polling) AND, how to do event read (in the on_comm art) in this languages.
I hve tested other project, that give for vb.net entry points in this way: on_read:, on_change:, on_connect:, on_disconnect. Is this possible by this dll too?
Thanks,
Feri
Hi,
I’ve been searching for about an hour for how to accomplish this - so many thanks for releasing something.
However I’m getting the problem that you mention earlier when I try to convert to a VS2008 solution. It gets an error on the diagram.cd file. Any suggestions for this? Thanks.
I’m a Delphi user
And a PIC18F user
I personally have a project with all this
I have been using Mikro Pascal to write my pic
This language is so much less messy and things get done faster generally for me when i have the tools.
Personalty I do not think we should write code to have limits if what go with what only. Manufactures need to be held competitive.
I personally see its much easier for Delphi users to get access through
*.OCX or a *.Dll file with what you have written.
But what impresses Delphi/Bourland users more is a HIDUSB.DCU file that no other exe files become necessary as its all in one *.exe.
I found a file HIDUSB.h and converted it with CTOPAS.exe
I also found windows at driver level does not generally like HID but at the same time found an event written in Delphi that identify’s USB devices being connected/disconnected. I have not tested it in HID USB devices yet.
I have just been looking at ActiveX in the MSDN (half a gig to install)
and their is .Net too that you like also.
.net is no good on single processor computers only mufti processor computers.
Theirs lots of single processor computers out their that are ideal to drive micro’s very well.
For those that do not use .Net (windows XP) can a number of DLL’s me copied and installed instead. is that a simpler option.
I’m considering doing this with activeX also as another option.
The reason that I like Axtivex personally is its more future proof as . net is changing to fast. And all will be throughen out with USB3 any way.
Its about getting the job done well to me and hitting the most end users.
Any way CtoPas.exe is windows based and can be found on TorryPages web site its easy to use if your C file complies ok.
points again
1/ your files run on PIC18F’s, Windows XP
2/ Can I help you to make a Delphi version after all every one should acknowledge the developers, as its free.
3/ I’m doing this for my Pic project and trying to combine a Delphi written program to support the Pic through the Pic’s HID interface. With out this my project will not work.
4/ The more you give developers the real code rather than handing it in *ocx’s or *DLL’s for the writters esteem the more developers are empowered to make better choices and more reliable products become. As the problem is MicroSoft are trying to make money off developers by not letting USB be open source.
And that hurts hobbyists like me.
I hope this is not seen as offensive but only a different developers opionion
running from a different language thinking how to make better good to all hobby devalopers.
J Lex Dean
Hi Florian,
Thanks for your code. We tried to connect it to one of our composite HID device and it was able to communicate with the device. However I am not able to capture the mouse events from the device. The mouse events were not coming in the eventhandler. Is there a way to handle the mouse events from the device?
It would be nice if you could provide a code snippet since I am new to device programming.
Regards,
Abraham.
I have my device connected and verified it in device manager under Human Interface Devices. Wrote this small C# console program and it doesn’t connect.
static void Main(string[] args)
{
USBHIDDRIVER.USBInterface usb = new USBHIDDRIVER.USBInterface(”vid_04d9″, “pid_e002″);
if (usb.Connect())
{
Console.WriteLine(”Device connected”);
usb.Disconnect();
}
else
{
Console.WriteLine(”Device not connected!”);
}
Console.ReadLine();
}
}
Any ideas?
I added the reference USBHIDDRIVER\bin\Debug\USBHIDDRIVER.dll to the project.
Thanks,
Clay
Well, how to make that fking simple read ???? Ok, i do start read, stop read, but I have no variable to tell me what the read data is..
Hello,
I didn’t understand everything about vendor and product ID… Can someone explain to me how can I see IDs of some HID device?
In my case I’m trying to connect PIC 18f***** to the PC…
Thanks…
Hi,
I have USB RFID Reader (which acts like a keyboard). I am able to connect to the reader but I am unable to read any data from it
myHidReader.write(bdata2)
Thread.Sleep(1000)
myHidReader.startRead()
myHidReader.enableUsbBufferEvent(New System.EventHandler(AddressOf readData))
myReaderHid.stopRead()
The event is never occurs
It seams that for my RFID reader HIDHandel is never created. Any possible reasons?
hi
I can’t download HID USB lib. it’s error is :
………………………………
— Your client does not have permission to get URL /p/csharp-usb-hid-driver from this server. –
………………………………
please give me other link …
or
send it to my e-mail :
i30t.ir@gmail.com
it is necessary for me !
thanks
awesome thanks for all the stuff, works great!!!
Hi all,
i’ll tried the code myselfe. Without success.
I write in response to “Clay says: March 12, 2010 at 17:26″
I think i got the same problem. I tried to figure out what happens, but i can’t get into it. What i found out is, that i don’t geht any device if i create an instance of USBInterface with valid vid and pid.
Any suggestions what to do? Thanks for any help.
Hi,
i solved the problem
I think it is a vista 64 problem.
I needed to replace all int* with IntPtr. Therfore i needed to adapt “null” to IntPtr.Zero.
Additionaly i needed to adapt myPSP_DEVICE_INTERFACE_DETAIL_DATA.cbSize = 5; to
myPSP_DEVICE_INTERFACE_DETAIL_DATA.cbSize = 8;
Right now i find a hid device. But i don’t know how to read data from the device. The only thing i can do is to catch the receive - event.
nears
Sorry for my one man show in your blog.
I found the solution in your sample code.
I did not see it the first time because i thought i would get the data out of my USBInterface-object. Why do i need to read it out of a static buffer? Is there no possibility to give the data to every single instance?
I got i nother problem. When i try to disconnect the device, i get an asert in:
public void disconnectDevice()
{
usbThread.Abort(); <————————————–Assert
myUSB.CT_CloseHandle(myUSB.HidHandle);
}
What is the usbThread for? Why do i need to abort it?
If i don’t do it, i’ll end up in a infinite loop. Any solutions for this “issue” ?
Hello,
i didn’t find Human Interface Device(HID) under USB section i am using Windows XP SP3 v. 3311
I added the reference USBHIDDRIVER\bin\Debug\USBHIDDRIVER.dll to the project.
i have written small piece of code and it doesn’t connect.
static void Main(string[] args)
{
USBHIDDRIVER.USBInterface usb = new USBHIDDRIVER.USBInterface(”vid_05ac”, “pid_1291″);
if (usb.Connect())
{
Console.WriteLine(”Device connected”);
usb.Disconnect();
}
else
{
Console.WriteLine(”Device not connected!”);
}
Console.ReadLine();
}
}
Actually i want to connect iPhone and read file sent from iPhone and write file to iPhone
Any ideas?
Please Suggest
Sachinc
Hi all
I am new to USB programming,
Can any one help me out
1. How to read feature reports
just need steps required to get the data.
thanks
ex:
if in c, i want to read a file
steps for that is
FILE * p = fopen(”….”);
fread(…..)
fclose();
in this pattern thans
I want to tell you guys I have just one windows api statment to reuse from a windows dll and I have the nessary data to get the PID VID and path data
for the usb devices. then the rest is easy I expect.
Lex Dean
Howdy there,Awesome blog post dude! i am Fed up with using RSS feeds and do you use twitter?so i can follow you there:D.
PS:Have you thought about putting video to the blog posts to keep the people more entertained?I think it works.Kind regards, Tim Moultry
Can anybody help me how to set up EasyHID.exe software and how to use it in interconnection my PC with PIC 18F4550 ?
plz help me to detecte N° port usb (capteur) to transfer file for pc
Hi,
I really appreciate that you have taken the time to develop this for the community. Please keep that in mind as you read the following.
What you’ve written here is extremely poor code. In addition, you have built the project based on other poorly written code.
Almost nothing here actually works, except in specific scenarios.
Your thread-handling is very poor and error prone. You don’t use any thread safety techniques.
Why is usbBuffer a static property? It should be a property of the USBInterface class, and it should only recieve data sent to the specific USBInterface object (not ALL connected objects). And it should be based on a Queue mechanism, not an arraylist.
You should expose a Connect(path) method that allows you to connect to a specific device based on its path or guid. MANY devices (even simple ones) install multiple HID instances that have the SAME pid and vid. Your code does NOT allow anyone to connect to any but the FIRST one. What happens if you have two similar devices attached? It is SO easy to do this much better than you have done it. I just can’t understand why it is so poorly written.
Take this for example: Thread.ThreadState.ToString()==”Running”
WHY WHY WHY? Why spend the extra time converting to a string? That is absurd and outrageous. Just do
Thread.ThreadState==ThreadState.Running
Come on, this is C#, a sophisticated language with great exception handling and thread-safety capabilities.. You act like it is some primitive form of VB.!!!
I hate to be so mean, and normally I would say it was a great and noble deed for you to have posted this. But the reality is that most of the people here would have done better just to keep browsing for another option. You’re code has actually hurt them by introducing so many terrible potential errors!
Hi Rich,
thanks for your comment, you are absolutely right about the poor style of the code, there are many things that one could improve easily unfortunately I lack the time and the test device to do so. But any one who is interested in contribute to the code, please send me an eMail or post a comment here and I will give you access to the repository.
To be honest when I developed the “library” in 2006 I would never have thought that it will still be used in 2010. At the time it was developed for Windows XP, it worked with Windows Vista and works now with Windows 7 without a lot of maintenance. I see this project as something I want to provide to everyone who wants to educate himself on USB HID programming and needs some starting point.
If you know of better libraries I will be happy to link them or as already said if you want to contribute to the project please let me know.
Florian
Hi!
I’ve tried this code to get all USB Devices plugged in:
USBHIDDRIVER.USBInterface usbI = new USBInterface(”");
string [] list = usbI.getDeviceList();
but list.Length is still 0. Why?
Can you help me?
thanks…
Jey
I’m using the code below and it works great. The problem that I’m running into is the event handler is always returning two values. It seems like it has a button_press value and then a button_up value. The button_up returns the same value every time. Is there an easy way using the class to ignore the button_up or return value?
//Code
//event handler
usb.enableUsbBufferEvent(new EventHandler(usb_DataReceived));
void usb_DataReceived(object sender, EventArgs e)
{
this.Invoke(new EventHandler(delegate { ProcessBuffer(sender); }));
USBHIDDRIVER.USBInterface.usbBuffer.Clear();
}
private void ProcessBuffer(object sender)
{
USBHIDDRIVER.List.ListWithEvent list = (USBHIDDRIVER.List.ListWithEvent)sender;
Byte[] b = (Byte[])list[0];
//where I can print the values out.
}
Hi Florian i’ve started with MAX3420E and I ‘m having some kind of problems first.
1-My device isn’t being recognized by the PC. Do I need to do some kind of configuration for the MAX to be recognized by the PC? Do I need to set Vbus and Vconnect or not?
2-What else do I need to do for the Pc recognizes the device.Because when I plug MAx into the usb port nothings changes at all. It’s like no device has benn put on it.
Hi Florian,
I ‘m working with your DLL into an C# project with visual studio 2005.
In the previous post several person’s tell they have problem’s withe the write method, it’s my case :
1-i see my device innto the windows device manager as HID device
2-when i send get device list method, it’s ok
3- if i try to connect with my device, the connect method return TRUE,
but when i try WRITE(), i have en FALSE returned,
please someone can help me, help us i don’t know what to do ?
fabrice
Hi,
First of all, Thanks for giving the valuable resource. I’m using your HID library code. I integrated your library codes in my windows applications. I received the data perfectly from my “Dictaphone” as an input device (Version 2.0.3). It works great. I update my input device files from “Power MIC II firmware upgrade tool”, after updates your code doesn’t get any data’s from that input device.
Thanks & Regards,
V.M. Damodharan
Hi,
First of all, Thanks for giving the valuable resource. I’m using your HID library code. I integrated your library codes in my windows applications. I received the data perfectly from my “Dictaphone” as an input device (Version 2.0.3). It works great. I update my input device files from “Power MIC II firmware upgrade tool”, after updates your code doesn’t get any data’s from that input device. Please help me i want to do this application with all versions.
Thanks & Regards,
V.M. Damodharan