HID USB Driver / Library for .Net / C#

Table of Contents

– Motivation

– The Human Interface Device Class

– USB Specific Stuff

– 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?

You can download the library here.

342 thoughts on “HID USB Driver / Library for .Net / C#”

  1. Hi!

    Where can I get this HID USB Driver?

    Can you send it to me???

    Thx and have a nice day! Dennis 🙂

  2. 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?

  3. Florian Leitner

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

  4. 🙁 I tryed lblHID.DataSource = USBInterface.usbBuffer and im getting empty array. How does the buffer works? Does it read every port or it reads the port that is opened automatically? Can you post full working code that reads usb data. Also how does this reading deals with USB addreeses, like my USB has 2 temperature sensors, If i use your DLL should I get all sensors data or should i request spesific address of the sensor (some how)?

  5. <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()

  6. Guillermo Odone

    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.

  7. Florian Leitner

    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

  8. 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.

  9. Florian Leitner

    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

  10. 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.

  11. Kurt Fankhauser

    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.

  12. Florian Leitner

    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?

  13. Kurt Fankhauser

    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.

  14. 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 😉

  15. Alberto Ramacciotti

    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.

  16. Florian Leitner

    If you want to use the Event mode just add this:

    usbI.enableUsbBufferEvent(newSystem.EventHandler(myEventCacher));
    usbI.startRead();

  17. Alberto Ramacciotti

    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)

  18. Florian Leitner

    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.

  19. 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

  20. 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!

  21. 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.

  22. Florian Leitner

    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 😉

  23. 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

  24. 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

  25. Brian Wessberg

    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

  26. 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
    0x00 LENGTH Anzahl der Daten
    0x01 BOARDTEMPL Boardtemperatur
    0x02 BOARDTEMPH
    0x03 PACKETNUMER Paketzähler 8Bit
    0x04 COMMAND Befehl
    0x05 ungenutzt ungenutzt
    0x06 DATA Daten 56Bytes


    0x3E ChecksumL 16Bit Prüfsumme(als 2er Komplement gespeichert)
    0x3F 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

  27. Florian Leitner

    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

  28. Florian Leitner

    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

  29. 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

  30. Florian Leitner

    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

  31. 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

  32. 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?

  33. 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?

  34. 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

  35. 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

  36. 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

  37. 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.

  38. 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

  39. 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

  40. 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

  41. Florian Leitner

    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

  42. 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

  43. Florian Leitner

    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

  44. 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.

  45. Florian Leitner

    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.

  46. 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!!!

  47. The numbers are embedded in the other numbers. Sorry to have side tracked you here.

    Thanks

  48. 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.

  49. 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.

  50. (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

  51. 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.

  52. 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

  53. 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

  54. 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.

  55. 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.

  56. 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

  57. 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

  58. 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?

  59. 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

  60. 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.

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

  62. 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.

  63. 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;
    }
    }
    }

  64. 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!

  65. 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);

    }

  66. 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

  67. 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

  68. 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

  69. 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?

  70. 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

  71. Pingback: Anonymous

  72. 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

  73. 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.

  74. Florian Leitner

    Hi M. Ilyas,
    unfortunately the access to keyboard / mouse is blocked by the operating system.

    Regards,
    Florian

  75. 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

  76. 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

  77. 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

  78. 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

  79. 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.

  80. 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.

  81. 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

  82. 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!

  83. 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.

  84. Florian Leitner-Fischer

    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

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

  86. 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 0x1DD2, product 0x102, version 0x16 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

  87. 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.

  88. 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?

  89. 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

  90. 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?

  91. 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”);

  92. 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

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

  94. 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

  95. 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

  96. 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 ?

  97. Florian Leitner-Fischer

    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.

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

  99. Florian Leitner-Fischer

    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.

  100. 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();

    }

  101. 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.

  102. 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?

  103. 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

  104. 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.

  105. 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

  106. 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.

  107. 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

  108. 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..

  109. 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…

  110. 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

  111. It seams that for my RFID reader HIDHandel is never created. Any possible reasons?

  112. PLEASE HELPE ME

    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

  113. 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.

  114. 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

  115. 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” ?

  116. 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

  117. 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

  118. 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

  119. 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

  120. Can anybody help me how to set up EasyHID.exe software and how to use it in interconnection my PC with PIC 18F4550 ?

  121. 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!

  122. 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

  123. 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

  124. 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.
    }

  125. Leonardo Vieira

    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.

  126. 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

  127. 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

  128. 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

  129. 2 Things to notice:

    vid is lower_case_sensitive
    e.g. write “vid_c251” and NOT “vid_C251”

    the device has to handle 64 byte hid-reports .. mine originally only supported 8 byte and i had to put it up to 64 byte to work. maybe you can modify the library to send smaller write-commands

  130. Hallo Florian,

    i have a problem with my HID.
    I am working with a Keil Cortex LPC 1768 Demo Board.
    The sample software in the Controller and the C++ Sample software on the PC works well. I can write and read.

    I made a c# program, and use your dll.

    Now I can connect, but never send.
    The USBSharp.WriteFile(….) returnes false.

    This is the same problem like in comment 38, 47, 75 and 149.

    Do You have any idea for a solution?

    Thanks & Regards,

    Christian

  131. Hello Florian,

    great work! I was finally able to receive data from my eDio Multi Remote device (remote control) – there are no working drivers .. at least none worked for me, so I decided to write my own.

    I’ve a minor problem though: I connect to the USBInterface in my Form_Load()-event (C#). It’s also the event where I do myDevice.startRead(). I assigned an event that is triggered whenever I press a button on my remote – works well.

    Now if I close the form I call myDevice.stopRead() and set myDevice to null. However it still requires a single press on my remote control (no matter what button) to actually terminate the program.

    Do you have any idea what I might be doing wrong?
    Thank you very much.

    Igor.

  132. Hi people, I have been using this library for hours, I connect and read from the device sucessfully but I am unable to read, ok, After hours of try and error I notice tthat some devices (like mine) receive the byte array and its values in hex base, so I find that a WriteFileEx function exist but is not declared in the USBSharp class, so I have don’t try this yet but I think it is the solution to the wrie problem. If any of you try this and can confirm please feedback. And Florian, thanks for the project 🙂

  133. Hello Florian,
    I got the same issue as on comment 38, 47, 75, 149 and 154. However I worked with TI, MSP430 HID sample code on the other side of USB. I found following details:
    1. The total package is 64 as reported on CT_HidP_GetCaps. Using a different size cause a write error.
    2. The first byte contains remaining length which is 63.
    3. Sometimes a error happened (see GetLastError()) due to IO load (ERROR_IO_PENDING). Use WaitForSingleObject() with timeout.
    I hope this hints help.

  134. Hello Guenther Klenner,

    the package length is the reason for the problem.
    For a test I transmitted only 2 Bytes to my Cortex-Controller and it works.
    Now I am back in the race.

    Thank you for helping.

    Christian

  135. Hello Florian,

    I’m trying to use this library. But I have te same problem as some other people have/had.
    I’m using a USB barcode scanner (which the pc recognises as a Keyboard device). But what I would like to know is:
    Has someone found a solution to make this also be detected (by the way, when I connect to the device it can connect). And to make it possible to read the data send by the barcode scanner.

    Or is there a way to install the device and not make it recognised as a keyboard device.

    Hope someone has the answers.

    Kind regards

    JKorsten

  136. Florian,

    I just wanted to say how great it was that you shared this code. It is great! Thanks so much.

    Brendan

  137. Hi Florian, your library is great! I finally understand how I can communicate to an USB device. But, I have a little problem: I can write data from the PC to the USB device (I use a Microchip PIC 18F4550) but I cannot read the usbbuffer. I know it´s receiving data (I tried with the USB monitor and the counter from usbbuffer) but I can´t read the data in usbbuffer. I´m using Visual Basic 2008 and I will very very greated with you if you can write a little example code to read any data and save it in a string. I´ll apreciate that.

    Greetings from Lima-Peru, and sorry if my english is bad

  138. I have composite device with two interface. How should I communicate with each inteface seperately. How should I specify inteface while using writeFile and readfile API?

  139. I don’t understand how you collect the data you have read? when you start.read(). Where does that data go?

  140. Great simple library. Worked right off the bat using events. Only thing I had to change was to making sure that the internal DevicePathName’s and any deviceID’s being compared to it are in the same CASE. Saw the same problem with similar libraries. The device id’s and vendor id’s are not always in the same case to the system. Make sure you convert them.

  141. Jason,

    Any example code to actually see how you read the device and how it stored the info??

  142. Jason,

    Any example code to actually see how you read the device and how it stored the info??

  143. Pingback: Código. Código Fuente. Como conectar un dispositivo vía USB | Actualidad

  144. Rafael Ghelardi(Brazil)

    Dear Florian,
    I’ve a code bar reader, that work’s like a hid device, I need that the values read from this device come record only to my DB, and not to where have focus. Do You have some example for this??I’m using Visual FoxPro
    I really thanks if you help me.

  145. Great work!!

    I am new in this HID USB library stuff .I am getting no errors, no warnings but still getting this message while compiling the code

    “A project with an output type of class library cannot be started.

    In order to debug this project,add an executable project to this solution which references the library project.Set the executable project as the startup project. ”

    I also made USBHIDDRIVER as a startUp project and set output type as class library. But still not getting any output and above message appears on compiling.

    Please someone help!!!thanks

  146. First,

    thanks for your work and efforts to putt it free for the internet community.
    I’m just curious about your motivation to replace FTDI chips by MAX3420E
    FTDI driver,chips problem itself or specific needs?

    Thank You

  147. Florian,

    Thank you for your contribution with the USBHID library.

    I am attempting to interact with a Magnetic Stripe Card Reader/Writer (Model#: MSR905H)

    As such, I have implemented your library in Microsoft Visual Basic.NET 2010 Express.

    I am sure that I am using the correct Vendor ID and Product ID

    I have used Device Monitoring Studio and I saw the hex commands being sent to the device

    Below is the code that I am using

    ———————– Beginning of Code ———————–

    ‘Declare byte array to store hex commands
    Dim var_Command(255) As Byte

    ‘Declare instance of USBInterface class and intialize with Vendor ID and Product ID of USB device
    Dim ins_cls_USBInterface = New USBInterface(“vid_10c4”, “pid_84b1”)

    ‘Connect to USB device
    ins_cls_USBInterface.Connect()

    ‘Insert hex commands into byte array
    var_Command(2) = &H1B
    var_Command(3) = &H72

    ‘Write hex commands to USB device
    ins_cls_USBInterface.write(var_Command)

    ———————– End of Code ———————–

    The problem that I am experiencing, is that when I write the hex commands to the device, I do not get the expected response (i.e. A yellow led should turn on, on the device)

    Any suggestions?

    Thanks in advance,

  148. @john

    You are most likely getting that message because you are trying to compile a “class”, rather than a “program” that references the class.
    You therefore may have to create a blank “Console Application” or “Windows Form Application”, and reference the class in your chosen application.

    Hope this helps,

  149. hey florian-leitne,
    nice work man.
    I am interfacing pic 18F4550 with my pc through usb port.first I found it quite difficult but after a lot of googling,I found your page.nice work.but I am facing a little problem.kindly help me…
    the problem is im using visual studio 2005,I am creating c# project,then I am adding your “csharp-usb-hid-driver” to my project.now i write functions like “USBHIDDRIVER.USBInterface usbI = new USBInterface(”vid612,pid415″);” my c# compiler gives me a lot of error.not recognizing USBInterface.means anu thing
    I am new to C#.Bt exxperienced with Visual C++. so if any one tell me how to use this library with Visual C++ then i shall be extremely thankful….
    thanks for your time….

  150. Hoi Florian,

    klingt gut, deine DLL, nur kann ich diese leider nicht in mein .Net 2003 Umgebung laden.

    Hast du eine Lösung/Idee dazu?

    Wäre dir sehr dankbar!

    Grüsse aus der CH

  151. anyone help me plzzzzzz…
    I hav a problem regarding “usb.startRead();”
    I donnt know from where it will start reading data and where data will be saved???????????
    thanks…
    Tahir

  152. Hi everybody,

    I’am working with Visual Basic Studio 2010.
    If Someone make the translation into this language can he send me an example ?
    Thanks
    Olivier

  153. Hi everybody,

    I try to use the enableUsbBufferEvent method and it doesn’t work !

    Can you send me an example of using please ?

    Thanks

    Olivier

  154. Rafael Ghelardi

    Hi everybody, i’m trying to use the regasm command and it doesn’t work. I’m using win7 64 and develop under visual foxpro.
    I can not register the dll.
    Can anyone help me.
    Thanks

  155. hi, could any one tell me if this library would work on a fingerprint scanner
    i am using a digital persona (uareu 4500 series)
    any suggestion are very much welcome
    thanks and God bless

  156. Hi,
    I wanted to use this DLL for a USBHID and with AutoHotKey sw. I need the function index for that and unfortunately nor PE Explorer, nor dllexplorer managed to find functions in those DDL? How does it come?

    do I need any Csharp library installed?

    Best Regards
    Bruno

  157. Hello, I manage to startt using the library but i do not manage to connect to my USB HID device
    Can you give me any hint

  158. Hi there. I’m using this Lib in VC++2005
    Anyway, from the Alex’s code in 119 comment, he said he DID it right. I transfered that code into VC++2005, but I have some problems, please somebody help me

    ——————–code ————————-

    private: System::Void usbEventHandler(System::Object^ sender, System::EventArgs^ args){
    array^ bufusb=gcnew array(252);
    USBHIDDRIVER::List::ListWithEvent list;
    list.Add(sender);
    bufusb=(array ^)list[list.Count-1];
    }

    ————————————————–
    when i compile the code, the program run! But it has a fault at the line :
    bufusb=(array ^)list[list.Count-1];

    The VC++2005 states that :

    An unhandled exception of type ‘System.InvalidCastException’ occurred in usbreader.exe

    Additional information: Unable to cast object of type ‘USBHIDDRIVER.List.ListWithEvent’ to type ‘System.Byte[]’.

    ————————————————–
    So, some one know what’s going on this code, and how could i repair it, please please help me

  159. hi,
    ur library is really nice,but I couldn’t use it to disconnect and connect my usb webCame, here’s my code
    USBHIDDRIVER.USBInterface usi = new USBHIDDRIVER.USBInterface(“VID_0C45”, “PID_60195”);
    //listBox1.Items.Clear();

    string[] pp = usi.getDeviceList();

    usi.Disconnect();
    usi.Connect();
    pp is always 0
    do u have any idea for me
    thank u

  160. Mikkel Jørgensen

    I’m trying to use your dll to incorporate several barcode readers in a vb 2008 program
    But i’ve stumbled right at the beginning.
    I can’t even connect to one device with vid_05E0 and pid_1200.
    The getDeviceList works fine with vid_05, but a call like:
    barReader = New USBInterface(“vid_05”, “pid_1200”) fails.
    I also tried using the hex code for 1200 (4b0)

    Otherwise this seems to be an ideal dll for my use and I would really appreciate being able to use it.

  161. Everything works but I need to click my usb pedal one time after I connectUSB.stopRead()
    or the thread will no stop.

    Here’s what happens

    I call usb.stopRead() and after this the property dataReadingThread.IsAlive = true. It stays this way until I click the pedal and then it changes to dataReadingThread.IsAlive = false. I know when I call the stopRead method it schedules the thread to be suspended but It can’t complete until I click on more time.

    Any ideas?

  162. I like teas very much so I drink a lot of tea every day.
    What about tea?
    very nice drink ,no tea no life.

  163. Hello everyone
    I have a problem to read from usb
    this is my code with Visual C # Express

    private void button1_Click(object sender, EventArgs e)
    {
    USBHIDDRIVER.USBInterface usb = new USBHIDDRIVER.USBInterface(“vid_1234”, “pid_0001”);

    usb.startRead();
    Thread.Sleep(5);
    for (int i = 0; i < 200; i++)
    {

    this.textBox1.Text = USBHIDDRIVER.USBInterface.usbBuffer.ToString();

    Thread.Sleep(5);
    }
    usb.stopRead();
    }

    I see the text in the textbox1 “USBHIDDRIVER.List.ListWithEvent”
    Why?
    can you tell me where I’m wrong
    thanks

  164. thanks for your library,
    i want to use a barcode reader with usb. but your code can not connect to it, do you why?

  165. Hallo Florian,
    ich arbeite mit mehreren PIC-USB-µC-Geräten, welche alle die gleiche VID und PID haben.
    Nun stellt sich mir das Problem, wenn mehrere Geräte angeschlossen sind das richtige auszuwählen. Wo wird die Auswahl getroffen und wie kann ich sie beeinflussen?
    DANKE schon mal im Voraus für dein Kommentar!
    MfG
    Zeus

  166. 64 bytes “every microsecond” would be 64 MB/s; not 64 KB/s. So I assume that should read “every millisecond”.

  167. Hi Florian,

    I have some questions for you.
    My printer name is ZEBRA RZ400 300DPI , I am trying to connect through USB. Thus this “USBHIDLIB” Library support bi-directional communication(print status succeed or failed) ? please let me know how can I achieve this.

  168. Florian Leitner-Fischer

    Hi Bashkar,

    I doubt that this will work since the library only supports devices of the hid (human interaction devices) class.

    Regards,
    Florian

  169. Florian,

    Can you give me any good suggestion or any helpfull source code to achieve support for bi-directional communication(print status succeed or failed) through USB for Zebra printer.
    Thanks in advance

    Regards
    Bhaskar

  170. hi
    i wana ask 1 thng ..i wana interface a microcontroller vith usb port….wat firmware needed for it

  171. hello sir,

    i am importing hid.dll library in vb 6.0 ,but couldt get this your this construction
    “Create a .bat file in the directory of the USBHIDDRIVER.dll and write the following command into it. Then run the bat file”

    where is this USBHIDDRIVER.dll ? and i have searched already hid.dll in system32.

  172. Hallo Florian und andere Mitleser

    ich arbeite gerade mit TI MSP430 HID Geräten und bekomme beim schreiben
    immer ein False zurück, verbindung und getdevicelist sind ok und melden
    das richtige zurück.
    Hätte hier einer ein kleines Testprogramm in VB NET ich stehe hier irgendwie auf dem Schlauch oder es ist noch ein Fehler in der Kommunikation.

    Gruß
    Cncfred

  173. hello,
    Nice job. I’m trying to use this dll for interfacing an home made usb hid device.
    I’ve got a very strange problem. I’m using mvvm pattern ( Visual Studio 2010- C# – MVVM ligth toolkit – .NET4 Framework).
    I have a model for querying my usb device. Simple class with an default construtor like :
    public TemperatureModel()
    {
    usb = new USBInterface(“vid_04d8”, “pid_003f”);
    _InterfaceConnected = usb.Connect();
    if (_InterfaceConnected)
    {
    usb.enableUsbBufferEvent(new EventHandler(TraitementReception));
    }
    }

    If I run test (Visual studio unit test) all is running fine, usb.Connect return true.
    but when I call the same constructor from the interface, the same constructor always return false.
    If I’m using code behind, the constructor is Ok and usb.Connect return true.
    Do you have any ideas ?

    Regards

  174. First off, thank you for the great driver! I almost have it working, I’m hoping you can provide more insight into the thread that reads the data. Data could come across my device at any time, so I’m doing something simple like this:

    {
    USBHIDDRIVER.USBInterface usb = new USBInterface(myvid,mypid);
    if (usb.Connect())
    MessageBox.Show(“connection!”);
    else
    MessageBox.Show(“FAIL”);

    usb.enableUsbBufferEvent(new System.EventHandler(myEventCacher));
    usb.startRead();
    }

    private void myEventCacher(object sender, EventArgs e)
    {
    string content = e.ToString();
    MessageBox.Show(content);

    }

    I can connect to the device, however, the myEventCacher event never fires. I must be doing something wrong thats simple but cant find it. Can you please provide code for the event callback and maybe an example of how to best parse the data?

  175. Wonderful blog! I truly love how its easy on my eyes and the information are well written. I am wondering how I can be notified whenever a new post has been made. I have subscribed to your rss feed which ought to do the trick! Have a nice day!

  176. Thanks for your work on this!

    I’m not very familiar with Byte arrays. If I need to send ASCII text commands to my
    device what options do I have?

  177. Hi!

    I have a particular problem here. I’m using PIC2550 to interface with my PC. So far, connectivity is just fine, write() method works, but! My PIC’s task is to send 64 bytes of 0 – 63 as values but I receive only 2 of them the first one (which is 0) and the package termination 0 byte. Any guess why’s not working?

    Thank you in advance

  178. Hello

    I cant write to my interface using usbdevice.write() in vb2008. What kind of type that data must be? I try byte, integer and array…

    If somebody can add here sample how send data in vb2008.

    Thanks.

  179. Hey Florian, super Bibliothek
    aber wie fülle ich den usbbuffer??

    USBHIDDRIVER.USBInterface USBi = new USBInterface (“vid_0b6a”, “pid_0022”) gelesen
    usbI.Connect ()
    usbI.startRead ()
    Thread.Sleep (5)
    for (int i = 0; i <200; i + +)
    {
    / / Mach irgendwas mit USBHIDDRIVER.USBInterface.usbBuffer HIER
    Thread.Sleep (5)
    }
    usbI.stopRead ()

  180. Anyone used this driver for the wireless playstation Buzz controllers?

    I tried but haven’t succeeded in writing to the buzzcontrollers (switching the Red lights)
    I can seem to connect to the controllers but not writing to them nor reading data from it?

    here is a piece of my code:

    bool bLight1 = true;
    bool bLight2 = false;
    bool bLight3 = true;
    bool bLight4 = false;

    USBHIDDRIVER.USBInterface usbI = new USBInterface(“vid_054c”, “pid_1000”);
    usbI.Connect();

    byte[] arrBuff = new Byte[8];
    arrBuff[2] = (byte)(bLight1 ? 0xff : 0);
    arrBuff[3] = (byte)(bLight2 ? 0xff : 0);
    arrBuff[4] = (byte)(bLight3 ? 0xff : 0);
    arrBuff[5] = (byte)(bLight4 ? 0xff : 0);

    usbI.write(arrBuff);

    The write() method keeps returning ‘false’

    How do I get this driver to work on the buzz controllers?

    regards
    nicci

  181. VS 2010 C# create and list work fine. write returns false with 87 (Parameter Error)

    All parameters look reasonable to me, length of report is 65.

    Result = USBSharp.WriteFile(hidHandle, ref outputReportBuffer[0], outputReportBuffer.Length, ref NumberOfBytesWritten, 0); // Result = false

    Int32 rc = Marshal.GetLastWin32Error();
    Debug.WriteLine(rc.ToString()); // 87

    I have example code that opens and writes the HID device using win32 just fine. I liked your C# class because I want to use C# and it is a lot cleaner than the example. I will post back if I am able to solve the problem myself before punting….

  182. Hi everybody, how about Set Report and Get Report features. Do you have any sample for these methods. ? How can I use USBHIDDRIVER.USBInterface or USBHIDDRIVER.USB.USBSharp for Set Report or Get Report functions. ? Thanks

  183. I am using a 64bit windows 7 using visual studio 2008. any idea why I cant connect to the RFID reader I have attached, or is just coz’ im using 64bit?
    heres my code:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    using USBHIDDRIVER;

    namespace ConsoleApplication2
    {
    public class Program
    {
    static void Main(string[] args)
    {
    USBHIDDRIVER.USBInterface usb = new USBInterface(“vid_05FE”, “pid_1010”);
    if (usb.Connect()){
    Console.WriteLine(“USB is connected.. yay”);
    }
    else{
    Console.WriteLine(“USB is not connected.. grr”);
    }

    Console.ReadLine();
    }
    }
    }

  184. Pingback: Visual Studio noob – Setting up my project with a library | SeekPHP.com

  185. I am using the TestFixture.cs in my program, this is my code here:

    USBHIDDRIVER.TESTS.USBTestFixture usb = new USBTestFixture();
    usb.startRead();

    The device connects, but the part where it is hanging up is the “Asert.isTrue(startCMD)” when trying to send the sendStartCMD(); in TestFixture.cs

  186. I want to interface pic18f4550 with Visual studio 2008 what is the procedure please tell me in details.
    Thanks in advance

  187. I want to interface pic18f4550 with Visual studio 2008 via USB.
    what is the procedure please tell me in details?
    Thanks in advance

  188. Florian Leitner

    friend I am working card data acquisition of temperature and humidity and energy consumption with pic 18F4550 and the interface and database for the’m done with c # 2008 but not as work as the dll and api besides I could not identify sending data to the pic hid the device and the host reconose and tells me that I have used and monitor connected USB device and identifies me but api and dll confuses me as I have guided examples are on the web and not how to import the dll to my project tells me that is not valid com tool nesecito please help me thank you in advance Vrinda.

  189. Thanks dude for giving such a wonderful open source tool… Because of ur dll i came to know a lot abt how usb works…. Most part of ur work was clear 🙂

    Btw what i actually wanted to ask is, “Am I allowed to edit the dll and add some custom classes for my game?” I am asking this because i wanna use this in Unity3d game engine, which is mono based so some of the classes are not supported and also i need to change the scope of some members so i can process it with inbuild unity function….. hope u get it!

    Anyway thanks again 🙂

  190. Hello Florian:
    I’m trying to connect with a GPS GARMIN GPSmap 76CSx through USB. I have only two lines:

    USBHIDDRIVER.USBInterface usb = new USBInterface(“VID_091E”, “PID_0003”);
    usb.Connect();

    but usb.Connect() always return false.
    Thanks in advance

    Regards
    Pedro

  191. I’m trying to connect with a GPS GARMIN GPSmap 76CSx through USB. I have only two lines:

    USBHIDDRIVER.USBInterface usb = new USBInterface(”VID_091E”, “PID_0003″);
    usb.Connect();

    but usb.Connect() always return false.

    ===========================================================
    try lowercase for the parameters

  192. Hello Florian,

    I am trying to connect with a vlotage regulater device by usb,
    the device send several kind of data which i need to read all of them and write them in a readable format.
    by using
    usb.read()
    how can i reach the data which i read?
    by the way i still new in programing, may be is simple question but…………!

    thanks
    R.H

  193. Hello Florian,

    first I want to thank you for this library but i’m having the same problems as Anish Thomas and I found your response to him and have tried using USB Monitor (e.g. http://www.hhdsoftware.com/Downloads/usb-monitor.html) to monitor the device but I don’t get any activity when using the usbhiddriver but when I use the program here http://charliex2.wordpress.com/2009/11/24/hacking-the-dream-cheeky-usb-led-message-board/ I can see activity.

    I’m able to connect to the device with your library but my writes always come back false.

    just wondering what else I might try.

  194. R.H.

    Look in the ..\csharp-usb-hid-driver\USBHIDDRIVER\TESTS folder of the dowload. There is an example of the code to use. Take the implementation of the myEventCacher method. Where it says “//DO SOMETHING WITH THE RECORD HERE” add your own code to read the data.

    My code looks like this:
    Console.WriteLine(currentRecord[0].ToString());
    Console.WriteLine(currentRecord[1].ToString());
    usb4.stopRead();

    The stopRead will throw a Threading.ThreadAbortException, so if you handle that properly, you get a way to exit from the thread that the event runs in. Use a timer to run startRead() method at intervals, or if you have code where you send data to the USB device and expect an answer, then run startRead() from there.

    Hopes this help.

  195. Has anyone found a way to get this to work with C++ I tried and I can pull all the files no problem I added an interface so I can use the MSDN example of
    #import “…\\USBHIDDRIVER.tlb”
    using namespace USBHIDDRIVER;

    HRESULT he = CoInitialize(NULL);
    InterfaceOfTheClass objectName(__uuidof(USBInterface));

    However I keep getting this error.
    First-chance exception at 0x774a070c in ConsoleApplication2.exe: Microsoft C++ exception: _com_error at memory location 0x0066ee64.

    Followed by
    System.Runtime.InteropServices.SEHException.

    Don’t know why any help is appreciated.

  196. Hello,

    Thanks for your great job.
    I have modified the interface to have an event when connection or deconnection and it seems that there is a memory leak in the method CT_SetupDiGetClassDevs () called from GetDevices ().
    Would you have an idea of ​​the problem?

  197. I have found the problem, you must add myUSB.CT_SetupDiDestroyDeviceInfoList(); just before retourning the arraylist in getDevices() method.

  198. I am a newbie to USB. This article helped a lot. My task it to design a middleware between application and windows USB class drivers for CDC ACM and CDC ECM (its a composite driver). Is there any user-mode client driver already available with Windows (like hid.ddl for HID class) whose APIs I can call from my middleware?
    I could see usb8023.sys drivers which I presume is kernel mode client driver.

  199. Pingback: » Blog Archive » Temperature USB Logger

  200. i want to send send data to pic18f4550, I am using VS2010, I connect to successfully but there is an error in writing, code is
    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;

    namespace WindowsFormsApplication2
    {
    public partial class Form1 : Form
    {

    USBHIDDRIVER.USBInterface USB = new USBHIDDRIVER.USBInterface(“vid_1234”);

    public Form1()
    {
    InitializeComponent();
    USB = new USBHIDDRIVER.USBInterface(“vid_1234”);
    }

    private void button1_Click(object sender, EventArgs e)
    {
    string dis;
    int i = 5;
    string[] list = USB.getDeviceList();
    try{
    for(i=0;i<=5;i++){
    dis = list[i].ToString();
    richTextBox1.Text = dis;
    }
    }
    catch{}

    USB = new USBHIDDRIVER.USBInterface(“vid_1234”, “pid_0001”);
    USB.Connect();

    if (USB.Connect())
    label1.Text = “CONNECTED”;
    else
    label1.Text = “NOT CONNECTED”;
    }

    private void button2_Click(object sender, EventArgs e)
    {

    byte[] byteArray = { 192, 65, 66, 67 };
    string str1 = System.Text.Encoding.ASCII.GetString(byteArray);
    string str2 = System.Text.Encoding.Unicode.GetString(byteArray);
    string str3 = System.Text.Encoding.UTF8.GetString(byteArray);
    string str4 = System.Text.Encoding.Default.GetString(byteArray);

    byte[] res1 = Encoding.ASCII.GetBytes(str1);
    byte[] res2 = System.Text.Encoding.Unicode.GetBytes(str2);//returns {192, 65, 66, 67}
    byte[] res3 = System.Text.Encoding.UTF8.GetBytes(str3);//returns {239, 191, 189, 65, 66, 67}
    byte[] res4 = System.Text.Encoding.Default.GetBytes(str4);//returns {192, 65, 66, 67};

    USB.write(res1);

    if (USB.write(res1))
    label2.Text = “send”;
    else
    label2.Text = ” Error”;
    }
    }
    }

  201. Hi Florian

    Great work.
    I have a problem I got an MCE IR device with 8 buttons normal keyboard driver cannot read os I would like to use your work. After reading through your forum I found it does not support keyboards WHY! and can it be changed so it can ?
    My device is “\\?\hid#vid_0471&pid_206c&col06#7&24c0929b&0&0005#{4d1e55b2-f16f-11cf-88cb-001111000030}” and windows installs the keyboard driver.
    Hope you can help.
    Christian..

  202. thank you for posting the code. it would be great if the companies that make these things would give sharing a try. it’s hard to even find basic information about these products. I believe there are 3 versions now. 1.0 is serial over usb, 2.0 is hid, and I saw a 3.0 on usbfever.com . I’ve rewritten some other code I found online to get the TEMPer 1.0 to work in visual basic 6, but I haven’t attempted anything hid yet. has anyone rewritten the code in vb6 and got it to work? here’s my email address http://mattsoft.net/myemail.gif I would extremely appreciate it if anyone could send me any vb6 code they have for the temper hid. even if you haven’t gotten it to work yet, maybe I can figure it out. when I get something working, I’ll post it on planetsourcecode.com

  203. I’ve found the problem with the Write() function!!! The HidHandle that is passed to the WriteFile Function is WRONG!!! So it hangs….

  204. Yes!!! The problem is that the hidHandle is created 2 times, so the second handler created is used for the WriteFile function… and since this handler points nowhere (on in a protected location, don’t know), I think, it hangs… For it seems that if during debug I force the first handler created in the WriteFile function everything goes well and the WriteFile returns 1!

  205. good work,
    I am using c# 2008, i am not able to send the data to usb , can u please him me on this , if possible cau u send me a working code.
    thank you.

  206. Hi Jedineon: I am now looking for some solution about false usbhid.write() function. I examined the USBHIDLIBRARY source code and I am not sure that the hidHandle is created two times. Are you sure? May you public your modification? If you have no possible place to publish the correct version, I offer to you that you can freely to publish it at our server http://www.mcu.cz.

  207. Hi!

    I am playing around with this lib and trying to hack the Dream Cheeky USB Panik Button. I can read the data and detect if the button is pushed or not.

    My problem now is: currently, I also have to run the original driver, as it seems to poll the button for its state … and I would like to do this myself.

    I have found out, that I would have to send
    Set report 00 00 00 00 00 00 00 02
    to it, in order to get the button state (doing so with e.g. SimpleHIDWrite.exe works fine).

    If I now want to use your write-method, it seems to fail.
    I get an “The supplied user buffer is not valid for the requested operation” error (implemented the windows error tracking:
    [DllImport( “kernel32.dll”, CharSet=CharSet.Auto )]
    public static extern int GetLastError();
    )

    Here is my piece of write code:

    Byte[] writeBytes = new Byte[8];

    writeBytes[0] = 0x00;
    //writeBytes[0] = 0x00;
    //writeBytes[1] = 0x00;
    //writeBytes[2] = 0x00;
    //writeBytes[3] = 0x00;
    //writeBytes[4] = 0x00;
    //writeBytes[5] = 0x00;
    //writeBytes[6] = 0x00;
    writeBytes[7] = 0x02;
    //writeBytes[0] = 2;

    bool ok = usb.write( writeBytes );

    ok is always false.
    Do you have any ideas?

    Thanks!

  208. Hi,
    First of all, I wanted to thank you for publishing the code. Saved me alot of work… I modified it a bit to allow to specify from “outside” the vendorId, and PID but otherwise works fine. But….(there’s always a but) after I encountered problems and narrowing it down a bit, I realized that it apparently doesn’t support 64-bit. So… my question is… (a) Have you added support for this ? (b) Can you point me to to what needs to be changed for 64-bit to work ? (c) Do you know of someone else that has had the same issue and may have resolved it ?
    Appreciate your help….

  209. Your usb driver for embedded system is very helpful for but I have a little problem.

    When WriteFile function (a function of krrnel.dll) is called,
    it also returns error.
    I got all true for usbconnection and CreatFile.
    The deive is Atmel at91sam3u4e. I think the device should return some ack to the host PC.
    Please help me to solve this problem. Thank you very much.

  210. i am working on a barcode reader… but i am using vb.net2008… some of the topics here are related to my problem but all the answers are written in c# i guess…

    my problem is that i dont know where to place my code

  211. Hi –

    I’m using a dsPIC33E and I can get the device to connect, but I’m having trouble figuring out how to read the data. When I send the command 0x37, I should get back a USB packet of 64 bytes. When I read usbBuffer[0].ToString() , it just gives “System.Byte[]”
    If I try to read usbBuffer[1] or greater, it gives the following error :

    Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index

    What am I doing wrong?
    Please help.

  212. Hi emandel,

    Have you got answers to your queries, if yes please share it with us. I am facing the same problem.

    What all things need to be done to run this application on 64 bit machine.

    Thanks in advance!

  213. Hi

    Can you help me in using this library in USB barcode reader.
    Please if you have any sample code for barcode using your library,please send me

    Thanks

  214. Hi vishal,
    Started to debug it but haven’t had time (maybe you have ?).
    The problem is all the calls to Windows DLL’s ReadFile, WriteFile etc. that use int instead of IntPtr….
    Eli

  215. Pingback: [#KINECTSDK] Kinect Missile Launcher (II): Moviendo el lanza misiles | El Bruno

  216. Pingback: [#KINECTSDK] Kinect Missile Launcher (II): Moviendo el lanza misiles - El Bruno

  217. MinisterOfTruth

    Hi,
    I have re-compiled the library in c# VS2010 and include the dll file as a project reference in my VB.NET2010 application. It works great.

    The only problem is shutting down. After myUSB.Connect() method is used, any subsequent myUSB.Disconnect throws an exception:
    {“Object reference not set to an instance of an object.”}
    Where the heck did it go? the MyUSB object shows itself as ‘IsConnnected’.

    As a result, My app won’t properly quit. There must still be a thread running as a result of not disconnecting.
    The myUSB.StopRead() seems to work ok.

    Last puzzle in an otherwise finished app.
    – Kirk

  218. Pingback: PIC18F4550, Giao tiep USB, Nap AT89S52

  219. Munna Kumar

    Hi How Can I write a window service to read barcode in background without using a textbox which is require to read barcode.

  220. hello
    while accessing the get device list into a string array ,,,,,,it is showing that the list is empty Or array is beyond the boundary limit even if i want to display array of zero ??????
    can anyone ans m please !!!!!

  221. Are you able to also release this under the LGPL? As it is a library, the GPL is a little too restrictive for the vast majority of Point of Service providers.

  222. Hi,

    You have made a great lib, it solves many pblms for those who work for usb

    I have add ur project as steps given, and made my form1 and included ur lib

    I have succesfully detected my pedometer, but can not read data

    All wroks well but hangs on Assert.IsTrue(usbI.write(startCMD)); in sendStartCMD

    Please guide where i am wrong

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;

    using System.Threading;

    using USBHIDDRIVER;
    using USBHIDDRIVER.TESTS;
    using NUnit.Framework;

    namespace USBHIDDRIVER
    {
    public partial class Form1 : Form
    { //pedometer
    USBHIDDRIVER.USBInterface usbI = new USBInterface(“vid_0590”, “pid_0028”);

    public Form1()
    {
    InitializeComponent();
    }

    [Test]
    public void deviceList()
    {
    USBHIDDRIVER.USBInterface usbI = new USBInterface(“0″);
    String[] list = usbI.getDeviceList();
    Assert.IsNotNull(list);
    }

    [Test]
    public void sendStartCMD()
    {
    byte[] startCMD = new byte[8];
    //Start
    startCMD[0] = 255;
    //Mode
    startCMD[1] = 0;
    //USync
    startCMD[2] = 28;
    //ULine
    startCMD[3] = 20;
    //tSync
    startCMD[4] = 20;
    //tRepeat – High
    startCMD[5] = 0;
    //tRepeat – Low
    startCMD[6] = 0x01;
    //BusMode
    startCMD[7] = 0xF4;
    //send the command

    Assert.IsTrue(usbI.Connect());
    Assert.IsTrue(usbI.write(startCMD));

    //textBox1.Text = textBox1.Text + ” AND ” + “from sendStartCMD”;
    }

    [Test]
    public void startRead()
    {

    sendStartCMD();
    usbI.enableUsbBufferEvent(new System.EventHandler(myEventCacher));
    Thread.Sleep(5);
    usbI.startRead();
    Thread.Sleep(5);
    for (int i = 0; i < 10; i++)
    {
    Assert.IsNotNull(USBHIDDRIVER.USBInterface.usbBuffer);
    Thread.Sleep(2);
    }
    usbI.stopRead();
    sendStopCMD();

    // textBox1.Text = textBox1.Text + " AND " + "from startRead";
    }

    [Test]
    public void sendStopCMD()
    {
    byte[] stopCMD = new byte[75];
    //Stop
    stopCMD[0] = 128;

    stopCMD[64] = 8;

    Assert.IsTrue(usbI.write(stopCMD));
    }

    [Test]
    public void userDefinedeventHandling()
    {
    sendStartCMD();

    usbI.enableUsbBufferEvent(new System.EventHandler(myEventCacher));
    usbI.startRead();

    //wait a little bit
    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);
    }

    // textBox1.Text = currentRecord;
    //DO SOMETHING WITH THE RECORD HERE
    }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    // USBHIDDRIVER.USBInterface usb = new USBInterface(“vid_0590″,”pid_0028″);

    // usb.enableUsbBufferEvent(new System.EventHandler(myEventCacher));

    //usb.Connect();

    String[] list = usbI.getDeviceList();
    textBox1.Text = list[0];

    foreach (string s in list)
    {
    textBox1.Text = textBox1.Text + ” ” + s;
    }

    sendStartCMD();

    usbI.enableUsbBufferEvent(new System.EventHandler(myEventCacher));
    usbI.startRead();

    //wait a little bit
    for (int i = 0; i < 10; i++)
    {
    Thread.Sleep(4);
    }

    sendStopCMD();

    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }
    }
    }

  223. Kirk,

    I also ran into the error when calling USBInterface.Disconnect(). Its because that function is calling Abort() on “usbThread”. usbThread is not actually created and used in the library at all. So boom! Null object reference. I modified the source to call Abort() on the actual thread (dataReadingThread) being used to read from the USB device.

    I am currently stuck on the issue that I see everyone is having. Once you start the thread reading from the USB device, the thread blocks on the call to ReadFile() waiting for the device to return data. This is fine since its in a thread. The problem is that when you shut down the application, this call to ReadFile() is still waiting and hangs the application so that it will not shut down properly. If I hit a button on my USB device (or unplug it), the call to ReadFile() returns and the app closes.

    I have tried calling Cancelio() which is supposed to cancel a blocking ReadFile() call but its not working. If I can just find a way to tell Windows to cancel that ReadFile() call we would be golden.

    I know others have been using the Environment.exit() call to force the application to exit, but I want to do it properly.

    Florian,

    Thank you for putting this out there. It has been a huge help!

    Kyle

  224. Keval,

    I do not see where your event handler “myEventCacher” is defined. This lib is event driven. All you need to do is tell it the name of the event function and then tell it to start reading data. When the USB device sends something to the computer, your event function will be called with the data.

    Simple example:

    using USBHIDDRIVER;
    using USBHIDDRIVER.List;

    // Initialize the USB Device for reading.
    protected void Initialize()
    {
    // Create a USB HID interface
    HID = new USBInterface(“vid_xxxx”, “pid_xxxx”);

    // If we are connected to the device, start listening for data (key presses).
    if (HID.Connect())
    {
    HID.enableUsbBufferEvent(HID_DataReceived);
    HID.startRead();
    }
    }

    protected void HID_DataReceived(object sender, EventArgs e)
    {
    ListWithEvent lEventList = (ListWithEvent)sender;

    // Do we have data?
    if (lEventList.Count > 0)
    {
    // Get a local copy of the byte array.
    byte[] data = (byte[])lEventList[0];

    string dataForDisplay = string.Join(” “, data.Select(x => Convert.ToString(x, 2).PadLeft(8, ‘0’)));

    // Do something here with the dataForDisplay string.
    }

    // Clear the event list so it doesn’t just grow forever…
    lEventList.Clear();
    }

  225. I just posted this over in the project issue tracker page, but wanted to make sure everyone saw it. I think I solved the application hanging issue.

    —-

    Since I really did not like the idea of using Environment.Exit(0) to solve this problem I took a look at the windows API calls involved. The actual issue was that the call to ReadFile() blocks execution and waits for data to become available. Since the call to ReadFile() is in a separate thread, using a blocking call is fine except that it will not stop blocking until it receives input. Even after we try to close the application, that thread is still waiting.

    I first tried to use the windows API CancleIo() to close the handle and make the ReadFile() function return immediately. This didn’t work because that function only works if it is called from the same thread as the call to ReadFile(). This is impossible since the thread is blocked! I then found CancelIoEx() which performs the same function as CancelIo(), but works from any thread no matter who owns the handle. It worked!

    I modified the function CT_CloseHandle(int hObject) to be as follows:

    public unsafe int CT_CloseHandle(int hObject)
    {
    HidHandle = -1;
    CancelIoEx(hObject, IntPtr.Zero);
    return CloseHandle(hObject);
    }

    To use this you will also need to define the CancelIoEx function as follows:

    [DllImport(“kernel32.dll”)]
    static public extern int CancelIoEx(int hFile, IntPtr pOverlapped);

    Kyle

  226. Yep, that’s why I prefixed my last post with “I just posted this over in the project issue tracker page”.

  227. I’ll right away clutch your rss as I can’t to find your e-mail subscription hyperlink or newsletter service. Do you’ve any? Please allow me realize so that I could subscribe. Thanks.

  228. Thanks sir,,,currently I’m do research about USB communication,,,and this article really help me,,,But actually I still don’t get it, is there another reference? Sorry I ask to much, but it will help me.

  229. Does anyone know how to connect a device with VB.net? I only see c# examples of code and am a little lost.

  230. Hi,

    I had the same issue when closing my application. Although Environment.Exit(0) can solve my problem but now I have to merge two projects I don’t want to use Environment.Exit(0) that will closed all my projects.

    I’m working on windows XP which is also not support for CancelIoEx() function. Is there any other way to solve this issue??

    Thanks,

  231. I like to read data from the device but the USBInterface does not contain function that allows me to read data and gave Miss displayed on console.Can someone help me please.

  232. Pingback: Khiêu vũ: RUMBA (TonyVan & Kim Phuong)

  233. how VID and PID are extracted/determined in this code.Any help please

    public USBInterface(string vid, string pid)
    {
    this.usbVID = vid;
    this.usbPID = pid;
    this.usbdevice = new USB.HIDUSBDevice(this.usbVID, this.usbPID);
    }

  234. Sam,
    You are supposed to know the vid and pid of the product you are working with.
    If you don’t, go to control, system, devices and see all the USB in your computer.each one will give you info about their properties, including the vid and pid.

  235. Hello RubenMisrahi,

    Thanks for reply. But I am encountering with other errror regarding “WriteFile()” .When Write File function is called is showing a error “cannot access protected memory” . I am trying to write to a USB HID. Can any one suggest me ideas on this.

  236. making the application in windows services using the usbhiddriver.dll. I made sample application, but I am facing the problem in usb.enableUsbBufferEvent(new EventHandler(usb_DataReceived)); this method. Here i am not geting the data from barcode reader device.

  237. Hi, Thanks for your API.

    I conect sucessful with the devide but i cannot write, get write false.
    I need to write 8 bytes with the feature id 00
    I have tested well with other applications, the api have a limitation or bug.

    Thanks

  238. Hello Florian,

    I am not sure if I can use your library fro our application.. We have a device that appears in Universal Serial Bus Converters as an USB device. This device (a RFID reader) writes its output to any keyboard entry program such as Notepad, Excel, Word etc. We have a Vb6 program that reads various Serial devices connected to com ports. We want to capture this device’s output from a virtual com port. Is this possible with your code? Thank you.

  239. Dear Florian Leitner
    Thanks for your useful help.
    You have said: “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).”

    How can I assign usbBuffer to a string,…. variable?

    Thanks for your kindly attention

    Hosseyn pakyari

  240. write function always returns false any help,
    I’m using pic18f4550 and it works properly on all other sofwares

  241. Hello,
    Well i want to know that i have web application in which i want to apply usb Smart card reader is their possibility for web based application .
    my code running on client side . but server side its detected server usb.
    i want to deteced usb client side .

    pls give some advice.

  242. Hi,

    Can I use it in my Silverlight project? Or do you have a compatible version for Silverlight?

    Thanks

  243. For everyone who has a problem with write() function which returns false. I found a bug in a source code. Brief introduction:
    I’m making device with MSP430 microcontroller from Texas Instruments. I had big trouble with usb.write() function. So I was debugging C# codes and found out that in HIDUSBDEVICE.cs in function writeData() is allocated byte array “OutputReportBuffer” of size 65 bytes (MSP device needs 64 bytes packet !!!). And also this function writes zero to the first byte of this array, so the function clears ID report number, which I put into first byte in the function usb.write(). But if I change size of array to 64 and delete line with zero to the first byte, everything will go well..

  244. I cant’ read anything from the device :/
    Here is my…
    [code]
    USBHIDDRIVER.USBInterface usb = new USBInterface(“vid_16c0”, “pid_05df”);
    usb.Connect();

    usb.startRead();
    byte[] RAW = (byte[])USBHIDDRIVER.USBInterface.usbBuffer[0];
    richTextBox1.AppendText(Convert.ToString(RAW));
    usb.stopRead();

    usb.Disconnect();
    [/code]

    How can I getReport from HID device properly?

  245. You didnt create event handler -> usb.enableUsbBufferEvent(new System.EventHandler(myEventCacher));
    Take a look into TEST folder of USBHIDDRIVER. Inside this folder is file textfixture.cs. This is a basic code for USB HID communication with USBHIDDRIVER class..If you want to operate with received data, probably you have to create a delegate function and invoke it from myEventCacher function..

  246. Exception when call Disconnect() function

    Here’s my code:

    USBHIDDRIVER.USBInterface usb = new USBHIDDRIVER.USBInterface("vid_0458", "pid_003a");

    bool isConneted = false;
    if (usb.Connect())
    {
    Console.WriteLine("Device connected");
    isConneted = true;
    }
    else
    {
    Console.WriteLine("Device not connected!");
    }

    Console.ReadLine();

    if (isConneted)
    {
    usb.Disconnect();
    }

    Here’s the exception:

    System.NullReferenceException was unhandled
    Message=Object reference not set to an instance of an object.
    Source=USBHIDDRIVER
    StackTrace:
    at USBHIDDRIVER.USB.HIDUSBDevice.disconnectDevice() in C:\Documents and Settings\Pham Xuan Loc\My Documents\Downloads\csharp-usb-hid-driver\USBHIDDRIVER\USB\HIDUSBDevice.cs:line 415
    at USBHIDDRIVER.USBInterface.Disconnect() in C:\Documents and Settings\Pham Xuan Loc\My Documents\Downloads\csharp-usb-hid-driver\USBHIDDRIVER\Interface.cs:line 88
    at csharp_usb_hid_driver_test.Program.Main(String[] args) in C:\Documents and Settings\Pham Xuan Loc\My Documents\Downloads\csharp-usb-hid-driver\csharp-usb-hid-driver-test\Program.cs:line 45
    at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
    at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
    at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
    at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
    at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
    at System.Threading.ThreadHelper.ThreadStart()
    InnerException:

  247. Pingback: Need a C# USB HID library for Visual Studio? Use this one! | Andrew's Sorry Sanctuary

  248. hello,

    I have a dictation device. It has a built in mouse ball.
    So, there are 2 devices that have the same VID and PID.
    How can I select the device with which I want to speak to.
    I just need to read data from there!

  249. Hi,

    Nice post.

    I am using magtek card reader (model no:21040108). I am using proper product id and vendor id. I am able to connect to device via this library, but not able to read data. Following event never triggers.
    obj.enableUsbBufferEvent(new System.EventHandler(myEventCacher));

    My device is listed under HID. It is hid keyboard device.

    Is it possible to read hid keyboard device? I think this library does not support same. Is there any other way to achieve this?

    THanks

  250. Hi everyone,
    I’m a newbie. I try to use your lib, but I have a problem: my eventHandler hass never ever fired. Any someone help me??
    Thanks all,
    Here’s my source:
    private void button1_Click(object sender, EventArgs e)
    {
    this.usb = new USBInterface(“vid_05e0”, “pid_1200”);
    Boolean res = usb.Connect();
    textBox1.Text = res.ToString();
    usb.enableUsbBufferEvent(new EventHandler(this.usbEventHandler));
    Debug.WriteLine(res);
    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]);
    textBox1.Text = i + ": " + byte_array[i];
    //MessageBox.Show(i.ToString());
    }
    Debug.WriteLine("");
    }

  251. I can not download library from your site in my country. for Please introduce another site for download.
    thank you very much.

  252. Hi Florian,
    zur Zeit bin ich auf der Suche nach einer Möglichkeit einen USB-Scanner in mein Programm einzubauen und bin dabei auf deine DLL gestoßen. Doch leider will er noch nicht scannen…Wo liegt mein Fehler:

    So hab ich ihn implementiert:

    USBInterface test = new USBInterface(“vid_080c”, “pid_0300”);
    String[] list = test.getDeviceList();
    test.Connect();
    test.enableUsbBufferEvent(new System.EventHandler(myEvent));

    public void myEvent(object sender, EventArgs e)
    {
    MessageBox.Show(“test”);
    }

    in der List wird er mir auch angezeigt.
    Doch wenn ich was Scanne passiert nix 🙁

  253. Hi Florian,
    I want to export the hid descriptor of an USB device.
    Can you suggest me how to do it.
    Thank you very much.

  254. Hi everyone, great lib thanks Florian !!
    I’m stuck here with these debug informations :
    FMO in searchDevice() : deviceID=vid_1493&pid_0019
    FMO in searchDevice() : myUSB.DevicePathName=\\?\hid#vid_1493&pid_0019#6&38a3d484&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
    FMO in searchDevice() : myUSB.CT_SetupDiEnumDeviceInterfaces()=1
    FMO in searchDevice() : myUSB.CT_SetupDiGetDeviceInterfaceDetail()=0
    FMO in searchDevice() : myUSB.CT_SetupDiGetDeviceInterfaceDetailx()=0
    FMO in CreateFile() : HidHandle =-1
    FMO in CreateFile() : DeviceName =\\?\hid#vid_1493&pid_0019#6&38a3d484&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
    FMO in CreateFile() : GENERIC_READ =2147483648
    FMO in CreateFile() : FILE_SHARE_READ =1
    FMO in CreateFile() : GENERIC_WRITE =1073741824
    FMO in CreateFile() : FILE_SHARE_WRITE =2
    FMO in CreateFile() : OPEN_EXISTING =3
    FMO in searchDevice() : myUSB.CT_CreateFile(this.devicePath)=0
    FMO in searchDevice() : deviceID=vid_1493&pid_0019
    FMO in searchDevice() : myUSB.DevicePathName=\\?\hid#vid_1493&pid_0019#6&38a3d484&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
    FMO in searchDevice() : myUSB.CT_SetupDiEnumDeviceInterfaces()=1
    FMO in searchDevice() : myUSB.CT_SetupDiGetDeviceInterfaceDetail()=0
    FMO in searchDevice() : myUSB.CT_SetupDiGetDeviceInterfaceDetailx()=0
    FMO in CreateFile() : HidHandle =-1
    FMO in CreateFile() : DeviceName =\\?\hid#vid_1493&pid_0019#6&38a3d484&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
    FMO in CreateFile() : GENERIC_READ =2147483648
    FMO in CreateFile() : FILE_SHARE_READ =1
    FMO in CreateFile() : GENERIC_WRITE =1073741824
    FMO in CreateFile() : FILE_SHARE_WRITE =2
    FMO in CreateFile() : OPEN_EXISTING =3
    FMO in searchDevice() : myUSB.CT_CreateFile(this.devicePath)=0
    usb.Connect() = True
    FMO in usb.write(Byte[])
    FMO in writeData() : getConnectionState()=True
    FMO writeData() : myUSB.HidHandle=-1
    FMO in Write() : deviceHandle=-1
    FMO in Write() : reportBuffer[0]=0
    FMO in Write() : Success=False
    usb.write(startCMD)= False

    It seems createFile isnt working properly with my env, hidHandle always equals -1 🙁

    If someone can help thanks 😉

    PS : I’m trying to communicate with a watch suunto ambit2 through usb

  255. another hint to solve my issue, if I use OPEN_ALWAYS instead of OPEN_EXISTING in createFile(), everything is OK only if I put this :
    deviceName = “USB#VID_1493&PID_0019#D983095115000600#{a5dcbf10-6530-11d2-901f-00c04fb951ed}”

    It means the deviceName returned by this lib doesnt get the right deviceName on my case…

    any tips folks ?! 🙂

  256. Hi folks, I found a mistake : connectDevice() is fired too times, to avoid this : just do USBHIDDRIVER.USBInterface usb = new USBInterface(); no need to launch usb.connect() it’s already done through new USBInterface() :

    public HIDUSBDevice(String vID, String pID)
    {
    //set vid and pid
    setDeviceData(vID, pID);
    //try to establish connection
    connectDevice();
    //create Read Thread
    dataReadingThread = new Thread(new ThreadStart(readDataThread));
    }

  257. Hi,

    Great library!! The only problem is that my device is listed as two separate items in the device manager and using usb.getDeviceList();. The two devices has the same VID and PID, so there is no way to separate them… I have tried the following:

    var usb = new USBHIDDRIVER.USBInterface(“0c45”, “7401”);
    var list = usb.getDeviceList(); // returns two items
    usb.enableUsbBufferEvent(new EventHandler(DataRecieved));
    Thread.Sleep(5);
    usb.startRead();

    but nothing happends… My device works is I use an application like ThermoHID, but I can’t get any data out of it using the library… Any suggestions? My device is a TEMPer1 (-40 – +120, with external sensor)

    Steinar

  258. Is there any working solution to use this library on a 64bit machine?
    I am using Windows 8 x64 and Visual Studio 2012. I can connect the USB-Device (return value is true), but the Write-Method always returns false.

    I also tried to set both projects (the usb lib and my test application) to x86, but I still get false as the return value.

    I hope you can help me.

  259. Hi,

    This library does not able to see my msp430 usb dongle. What can i do for this? Vid and pid are known but not in the list

    var usb = new USBHIDDRIVER.USBInterface(“_″);
    var list = usb.getDeviceList()

  260. Hi again,
    Does anybody know the solution?

    I really need an answer, my project is under stress,

    Thanks for reply.

  261. Hello, I’m using vs2012 on win8 x64. When I add reference tothis library on my WPF project, the view end in nullreferenceException, and I couldn’t manage my view, from designer. But the app is running, when I start it, or debug. I already have problem with the proper exiting, because the of the reading thread.
    Could You help me please?
    Thank You!

  262. .Net Developer

    Hi,

    This library does not able to find my device in Windows 8 64 bit OS and VS 2005. But I can able to find the device in Windows Xp using this application.

    var usb = new USBHIDDRIVER.USBInterface(“_″);
    var list = usb.getDeviceList()

    In windows Xp it works perfectly but in Windows 8 it does not find the device. the devicepath is null always. But I Can c the device in Windows 8 Device Manager.

    Please help to update what could be the issue,

    Thanks in advance.

  263. Hi!
    Will this driver support report size different of 64 bytes? My device desired for report size of 4 bytes and it can only receive data. Sending data failed all the time. Thanks in advance!

  264. Hi there,
    does anyone have a working VisualBasic 2005/2010 example?

    I got the device search working. But i have some problems using the event handler.

    Thanks
    Stefan

  265. I understand that there have been MONTHS of people asking for an update for Windows 8 64 bit with no replies. I am one such person, however I’m posting this comment just in case “Florian Leitner-Fischer” has been emailing out replies.

    Or if anyone else has a solution, please chime in.

  266. Florian Leitner-Fischer

    Hi everyone,

    I wrote the library back in the days of Windows XP, I’m actually quite surprised that the library still works with Windows Vista and Windows 7. Right now I’am not able to maintain the library, which is among other reasons due to the lack of time and due to the lack of hardware (I don’t have any USB HID hardware device that I could use with the library anymore).

    My best guess is that Microsoft made some changes in how USB HID devices can be accessed in Windows 8 an the library will not work with Windows 8. Nevertheless if anyone gets the library to work with Windows 8, please share the code and let me know!

  267. Hello Florian Leitner-Fischer,

    I am also using MAX3420E USB to read the data from microprocessor.
    I also want to develop a driver which read the data from the USB but i want in C++,because i am not aware of C#.

    I have downloaded the USBHIDDRIVER Code ,the code successfully complied by getting an error when tried to Debug.
    “A project with an output type of class library cannot be started directly.
    In order to debug this project,add an executable project to this solution which references the liberary project.Set the executable project as the startup Project”

    Where USBHIDDRIVER is my Startup project.Can you let me the solution as i am very new to the filed.

  268. rahman mohammadi

    your project can immense help me,
    but i have problem:
    why my event not fire? this is my code:
    public partial class Form1 : Form
    {
    USBHIDDRIVER.USBInterface usbI = new USBInterface(“vid_05f9”);
    USBHIDDRIVER.USBInterface usb = new USBInterface(“vid_05f9”, “pid_2506”);

    public Form1()
    {
    InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    String[] list = usbI.getDeviceList();
    usb.enableUsbBufferEvent(new System.EventHandler(myEventCacher));
    usb.Connect();
    usb.startRead();

    }

    private void timer1_Tick(object sender, EventArgs e)
    {

    }

    protected void myEventCacher(object sender, EventArgs e)
    {

    }

    }

  269. Hello Florian,

    i have a Problem with the “Data Receive Event”
    If i get more then 64 Byte (here 70 Byte) i only see the last incoming Bytes

    Her the Read Sorce Code:

    Dim currentRecord As Byte() = Nothing
    Dim counter As Integer = 0
    While DirectCast(USBHIDDRIVER.USBInterface.usbBuffer(counter), Byte()) Is Nothing
    ‘Remove this report from list
    SyncLock USBHIDDRIVER.USBInterface.usbBuffer.SyncRoot
    USBHIDDRIVER.USBInterface.usbBuffer.RemoveAt(0)
    End SyncLock
    End While
    ‘since the remove statement at the end of the loop take the first element
    currentRecord = DirectCast(USBHIDDRIVER.USBInterface.usbBuffer(0), Byte())
    SyncLock USBHIDDRIVER.USBInterface.usbBuffer.SyncRoot
    USBHIDDRIVER.USBInterface.usbBuffer.RemoveAt(0)
    End SyncLock

    Dim RealLength As Integer = 5 + currentRecord(3)
    Dim RealData As Byte() = New Byte(RealLength – 1) {}

    Array.Copy(currentRecord, 1, RealData, 0, RealLength)

  270. Hello Florian (excuse my grammar) , I ‘m using Windows 8.1 , its architecture is 64 bits, and I must say that everything was fine , until I tried to read the input buffer , could list the HID devices available , I could connect, could write data to a microcontroller ( 18F4550 ) to turn on and off a LED , however, when I try to read the data gives me an exception.

    The program made in the microcontroller work properly, both at the reception and sending data , as I tried on a software that features a HID terminal.

    I feel that the problem is in the way I try to read the data.

    Maybe you do not remember how the program did over five years, but if you remember anything I’d appreciate you to help me understand that part.

    I’m programming in Visual Studio 2013 with C #, it is the part I do not understand exactly:


    private void Lectura_Click(object sender, RoutedEventArgs e) {
    HID.enableUsbBufferEvent(myEventCacher);
    this.Recibido.Text += "Bytes:\n";
    if (HID.Connect() ) {
    HID.startRead();
    Thread.Sleep(5);
    for (int i = 0; i < 200; i++) {

    Thread.Sleep(5);
    }
    HID.stopRead();
    var buffer = USBHIDDRIVER.USBInterface.usbBuffer.ToArray();
    this.Recibido.Text += msg + bufferOut1.Length;
    this.Recibido.Text += " ";
    }
    }

    With this piece of code is supposed to try to read the input buffer and assign it to a variable “buffer” in a box deploy the buffer size and tells me it’s zero.

    I hope you can help me to complete a set of closed loop control.

    Tschüs.

  271. Write(arrbyte) is return is false, please tell me when this become false, i am trying from two days. But i am not getting read the report from the device.

  272. Hi there,

    I’ve discovered a problem with re-using this library multiple times from different instances of my calling class.

    Your static usbBuffer holds onto the event handler from my enableUsbBufferEvent call. Hence my calling object is never disposed and subsequent uses of your library from a new instance of my calling class raise events on the original (not disposed) object.

    The fix is simple: in module USBInterface, have the enableUsbBufferEvent() method store a private copy of its eHandler argument and then specifically unsubscribe to that event in the Disconnect() method.


    private System.EventHandler handler;
    public void enableUsbBufferEvent(System.EventHandler eHandler)
    {
    handler = eHandler;
    usbBuffer.Changed += eHandler;
    }

    public void Disconnect()
    {
    if (isConnected)
    {
    this.usbdevice.disconnectDevice();
    usbBuffer.Changed -= handler;

    }
    }

    Great library though – thanks for all your hard work.

    Robert

  273. Is there any way to access a specific device which shares the same VID/PID with 11 other?

    \\?\hid#vid_046d&pid_c52b&rev_1203&mi_02&qid_402d&wi_01&class_00000006&col02#9&1a639d15&0&0001#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&mi_01&col01#8&3442efb5&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&rev_1203&mi_02&col01#9&3b58cee6&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&rev_1203&mi_02&qid_2010&wi_02&class_0000001a&col01#9&224be6af&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&mi_01&col02#8&3442efb5&0&0001#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&rev_1203&mi_02&col02#9&3b58cee6&0&0001#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&rev_1203&mi_02&qid_2010&wi_02&class_0000001a&col02#9&224be6af&0&0001#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&mi_01&col03#8&3442efb5&0&0002#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&rev_1203&mi_02&qid_2010&wi_02&class_0000001a&col03#9&224be6af&0&0002#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&mi_01&col04#8&3442efb5&0&0003#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&mi_00#8&106bb1f3&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}
    \\?\hid#vid_046d&pid_c52b&rev_1203&mi_02&qid_402d&wi_01&class_00000006&col01#9&1a639d15&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}

  274. Hello, I’m Master Course student

    well, just I downloaded your Library and used it

    I connected HID with your Library successfully

    but Write() method return value was False.

    I want this solution of problem

    Thanks

  275. Hi,
    I use your C# USB HID library and I have problem. I don’t send data to my device with Write() method.
    Here is my example code :
    /*
    * Vytvořeno aplikací SharpDevelop.
    * Uživatel: FB
    * Datum: 5.11.2015
    * Čas: 6:32
    *
    * Tento template můžete změnit pomocí Nástroje | Možnosti | Psaní kódu | Upravit standardní hlavičky souborů.
    */
    using System;
    using System.Collections.Generic;
    using System.Drawing;
    using System.Windows.Forms;
    using USBHIDDRIVER;
    using System.Threading;

    namespace rele_karta
    {
    ///
    /// Description of MainForm.
    ///
    public partial class MainForm : Form
    {
    public MainForm()
    {
    //
    // The InitializeComponent() call is required for Windows Forms designer support.
    //
    InitializeComponent();

    //
    // TODO: Add constructor code after the InitializeComponent() call.
    //
    }

    USBHIDDRIVER.USBInterface rele_karta = new USBHIDDRIVER.USBInterface(“vid_16c0″,”pid_05dc”);
    byte[] odeslana_data = new byte[10];

    void Button1Click(object sender, EventArgs e)
    {
    odeslana_data[0] = 10;
    if(rele_karta.Connect())
    textBox1.Text = “Připojeno”;
    else
    textBox1.Text = “Nepodařilo se spojit se zařízením”;

    if(rele_karta.write(odeslana_data))
    textBox2.Text = “Odesláno”;
    else
    textBox2.Text = “Nepodařilo se odeslat data”;
    }

    }

    }

    Device is connected to PC and SW “see” device and connect device.
    Please, help me.
    Thanks

  276. Well i am using this for basic read/write purpose now i am receiving the input report from usb hid device but it is in byte array so is there any way to convert the input report into human readable form ??

    I’d tried type casting byte into char but it gives me out put : $$$$$ßB<1äúUUDëÿÖêïí ÿíx;?¥4Eü5eçùüz

  277. Domenico Barile

    Hi Florian
    I’d like to use your library to check if a stylus is “connected” to a tablet.
    I’m not sure to know ever the vendor ID of the stylus, do you think I could use it in any way ?
    Thank you
    Domenico

  278. Hi,

    i dont get any devices listed.
    Even when I run :
    USBHIDDRIVER.USBInterface usbI = new USBHIDDRIVER.USBInterface(“_”);
    String[] list = usbI.getDeviceList();

    The list is Length 0!

    I have a mouse an a USB Relay connected and they work.

    Any Idears what could be wrong?
    Thanks
    Flo

  279. Mohammed Noori

    Hi Florian
    thanks for your support,
    I need your support, I have ( Misiri MSR705 HiCo Magstrip Magnetic Card Reader Writer) device connect by USB HID, how can intergrade this deceive with VB.net to read data from card .

    Many Thanks

  280. Hello Florian
    Thanks for your great work.
    This library works great on windows 10, but It doesn’t work well on windows 7(write command doesn’t work). Any idea?.
    Regards

  281. Pavel Buzuluxky

    All greetings!
    I want to tell as has corrected “false” at use usb.write ().
    In file “HIDUSBDevice.cs” is “public bool writeData (byte [] bDataToWrite)”.
    There it is necessary to find and make comments on a line
    OutputReportBuffer [0] = 0;
    here so
    //OutputReportBuffer [0] = 0;

    And in a cycle:
    //Store the report data following the report ID.
    for (int i = 1; i <OutputReportBuffer. Length; i ++)
    {
    if (bytesSend <bDataToWrite. Length)
    {
    OutputReportBuffer [i] = bDataToWrite [bytesSend];
    bytesSend ++;
    }
    else
    {
    OutputReportBuffer [i] = 0;
    }
    }
    We change "int i=1" on "int i=0".

    Now we can compile library.
    Now at use usb.write () the first byte will be "Report ID".
    It is all.

    P.S. I am sorry for my English.

  282. This library does not able to see my USB. I attach all kinds of USB but nothing work. What can I do for this? Vid and Pid are known, but nothing happened. Here is my sample code. I add dll reference into my project. I am using VS 2012 windows 7. Please help me.

    USBHIDDRIVER.USBInterface usbI = new USBInterface(“VID_1A79”, “PID_7410”);
    String[] list = usbI.getDeviceList();

    connected = usbI.Connect();

    Assert.IsNotNull(list);
    Thread.Sleep(5);
    usbI.startRead();
    Thread.Sleep(5);
    for (int i = 0; i < 200; i++)
    {
    Assert.IsNotNull(USBHIDDRIVER.USBInterface.usbBuffer);
    Thread.Sleep(2);
    }

  283. For all who had problems with getting false with write() function:
    Length of output package have to be the same as in the USBHIDDRIVER.DLL declared. It is 8 byte or 64 bytes long – depend on dll ( I saw both source code versions ). I myself changed the dll, so that the output report uses the same length as input report, because the output report is mostly sent over control pipe.

  284. Hi
    I am new to C#, and so far after a LOT of searching, this appears to v=be the only HID interface that could work.

    Please has any one got a WORKING example ?
    I am using Microsoft Visual Studio 2010 – C#

    I have only two weeks of C# experience, so be Kind.

    Cheers

    Ceri

  285. Hello Mr.Leitner,

    Thank you for sharing this Library, it’s a great job.

    I m working with PIC18F4550, I need to establish a connection between the PIC and Unity3D(editor Visual Studio), The computer can detect the PIC and it show me the properties (Vid and Pid …..) till now all is ok.

    The problem :

    I m writing the program in C# in Unity3D (Editor visualstudio),
    The problem is : when i run this programm i get usbI.connect()=false, I don’t know if I misused the function!!!!

    I will be gratefull for helping me.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using UnityEngine;
    using USBHIDDRIVER;
    using USBHIDDRIVER.List;

    public class gg : MonoBehaviour {

    // Use this for initialization
    bool connected = true;
    USBHIDDRIVER.USBInterface usbI = new USBInterface(“vid_04d8”, “Pid_003f”);

    void Start () {

    connected = usbI.Connect();

    Debug.Log(connected);

    if (connected)
    {

    usbI.enableUsbBufferEvent(new EventHandler(Reception));

    Debug.Log(“Device connected”);

    }
    else {
    Debug.Log(“Device not connected”);
    }
    }

    // Update is called once per frame
    void Update()
    {
    }

    public void Reception (object sender, EventArgs e)
    {
    }
    }

  286. I am trying to use this library for reading Data from HID MSR Reader.

    So when card swipe happed Event Triggered and data received in (byte[])USBHIDDRIVER.USBInterface.usbBuffer[0]
    But problem is that too many extra bytes added in begining and end of actual data.
    can not find any exact pattern arround it.

    Can someone please advice on it how to use it with HID MSR Reader.

  287. Pingback: c# - C# et USB Périphériques HID

  288. Pingback: c# - C# y Dispositivos USB HID

  289. Pingback: Why am I getting the error "No module named 'AdapterLibrary'" - TechTalk7

  290. At gossipara , we strive to provide you with brief description Whether you’re here to know something new or experience something you are never told before we’re here to make your experience enjoyable and rewarding.

    Explore our sections/pages/features to find all the relevant gossip .

    If you have any questions or need assistance, please don’t hesitate to contact us. We’re here to help you every step of the way.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.