Click here to Skip to main content
15,860,972 members
Articles / Programming Languages / C#
Article

A USB HID Component for C#

Rate me:
Please Sign up or sign in to vote.
4.12/5 (86 votes)
22 Mar 2007CPOL1 min read 1.9M   68.4K   240   339
A component to communicate with a USB HID device

Introduction

This article is about a USB HID component which enables you to communicate with HID devices over USB. There is no default component available for USB at this moment, and this component should provide you with a good starting point when writing your own USB HID enabled applications.

This article provides a sample application as well as the component itself.

Background

The component is based on various sources. A good start for USB in C# is this website. Also the book USB COMPLETE (third edition) by Jan Axelson is a must read for anyone wishing to incorporate USB HID into her/his application.

The component is developed during a project at the Avans Hogeschool in 's-Hertogenbosch, The Netherlands.

Using the Code

In the provided sample application, there is a good demonstration on how to include the component. Moreover, the use of the component is very well demonstrated. The only thing that must be done in your own application is implementing the events.

You'll also have to override the following functions in your form, so that your program is USB aware. In the property box, you'll have to provide a vendor and product id of your USB device in order to detect the correct device.

C#
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e);
usb.RegisterHandle(Handle);
}
protected override void WndProc(ref Messagea m)
{
usb.ParseMessages(ref m);
base.WndProc(ref m); // pass message on to base form
}

Points of Interest

A mouse is always in use by Windows, and cannot be captured by your own application. This also applies to HID devices in use by other applications.

History

  • 22nd March, 2007: First version, currently in development

Updates will be posted if there is a need for them.

License

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


Written By
Web Developer
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerRe: SpecifiedDevice Pin
Member 1478500418-Apr-20 11:23
Member 1478500418-Apr-20 11:23 
QuestionHow to write data in USB HID device? Pin
Member 112767143-Dec-14 19:46
Member 112767143-Dec-14 19:46 
QuestionHow to support more than one device with similar PID and VID and different serial Pin
elekgeek1-Dec-14 20:36
elekgeek1-Dec-14 20:36 
QuestionSerial Number of HID device Pin
elekgeek30-Nov-14 0:03
elekgeek30-Nov-14 0:03 
AnswerRe: Serial Number of HID device Pin
Garth J Lancaster30-Nov-14 0:31
professionalGarth J Lancaster30-Nov-14 0:31 
GeneralRe: Serial Number of HID device Pin
elekgeek30-Nov-14 3:10
elekgeek30-Nov-14 3:10 
GeneralRe: Serial Number of HID device Pin
Garth J Lancaster30-Nov-14 10:09
professionalGarth J Lancaster30-Nov-14 10:09 
GeneralRe: Serial Number of HID device Pin
elekgeek30-Nov-14 20:20
elekgeek30-Nov-14 20:20 
It took me quite some time to figure how to do it, I still don't know if I did it correctly to be honest, here is what I did, I need your guidance to see if I did it wisely:

In Win32Usb.cs under #region P/Invoke, I added the following before #endregion:

C#
/// <summary>
/// Gets serial number of a HID device
/// </summary>
/// <param name="hDevice">HID device handle</param>
/// <param name="buffer">Buffer to fill with serial number</param>
/// <param name="bufferLength">Buffer length</param>
/// <returns>True if successful</returns>
[DllImport("hid.dll", CharSet = CharSet.Auto, SetLastError = true)]
protected static extern bool HidD_GetSerialNumberString(IntPtr hDevice, StringBuilder buffer, Int32 bufferLength);


then, I said to myself that I don't know how to go through setup and get the handle, so in HIDDevice.cs under #region Privates/protected, I added the following function just before #endregion, this function calls HidD_GetSerialNumberString and gives is the actual handle of the HIDDevice without requiring me to go through all the path reading and getting the handle again:

C#
/// <summary>
/// Finds a device serial number
/// </summary>
/// <returns>A device serial number</returns>
protected virtual string ReadSerialNumber()
{
    StringBuilder SerialNumber = new StringBuilder(127);
    HidD_GetSerialNumberString(m_hHandle, SerialNumber, 127);
    if (SerialNumber.Length > 0)
        return SerialNumber.ToString();
    else
        return "Device has no serial number!";
}


Now, in SpecifiedDevice.cs file, which is where I really want to get the serial, I added the following inside SpecifiedDevice class:

C#
public string SerialNumber
{
    get
    {
        return ReadSerialNumber();
    }
}

public override string ToString()
{
    return SerialNumber;
}


Now to test this code, I added these lines:

C#
if (usb.SpecifiedDevice != null)
{
    MessageBox.Show(usb.SpecifiedDevice.SerialNumber);
    lb_message.Items.Add(usb.SpecifiedDevice);
}


to become like this:

C#
private void btn_ok_Click(object sender, EventArgs e)
{
    try
    {
        this.usb.ProductId = Int32.Parse(this.tb_product.Text, System.Globalization.NumberStyles.HexNumber);
        this.usb.VendorId = Int32.Parse(this.tb_vendor.Text, System.Globalization.NumberStyles.HexNumber);
        this.usb.CheckDevicePresent();
        if (usb.SpecifiedDevice != null)
        {
            MessageBox.Show(usb.SpecifiedDevice.SerialNumber);
            lb_message.Items.Add(usb.SpecifiedDevice);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}



and it really works. I don't know if there is a better implementation, but this is my 3rd week learning C#, I think I did a good work!

modified 1-Dec-14 2:46am.

GeneralRe: Serial Number of HID device Pin
Garth J Lancaster1-Dec-14 17:24
professionalGarth J Lancaster1-Dec-14 17:24 
Questionerror or not? Pin
igorlisin10-Nov-14 2:54
igorlisin10-Nov-14 2:54 
QuestionI can not accept data Pin
Member 111120597-Nov-14 0:11
Member 111120597-Nov-14 0:11 
Questionthank you!! Pin
chuck in st paul23-Oct-14 4:02
chuck in st paul23-Oct-14 4:02 
QuestionAn unhandled exception of type 'System.IndexOutOfRangeException' occurred in UsbLibrary.dll Pin
Member 1111054828-Sep-14 12:07
Member 1111054828-Sep-14 12:07 
QuestionGreat work, but I'm having some trouble, could someone help me? Pin
Member 1104119625-Sep-14 3:36
Member 1104119625-Sep-14 3:36 
AnswerRe: Great work, but I'm having some trouble, could someone help me? Pin
Member 861492327-Oct-14 10:20
Member 861492327-Oct-14 10:20 
QuestionGreat work! Pin
newtonsrl31-Aug-14 5:18
newtonsrl31-Aug-14 5:18 
Questionhow to send input on in-endpoint? Pin
jeffery c7-May-14 17:11
jeffery c7-May-14 17:11 
QuestionHow catch event from ConsoleApplication? Pin
Member 1062141925-Feb-14 4:08
Member 1062141925-Feb-14 4:08 
QuestionHow to connect USB HID device which doesn't have Product ID and Manufacture ID Pin
avisatna2-Feb-14 21:10
avisatna2-Feb-14 21:10 
GeneralMy vote of 3 Pin
Mic8-Aug-13 13:45
Mic8-Aug-13 13:45 
QuestionUsbLibrary in WPF application Pin
hassan azizi4-Aug-13 20:01
hassan azizi4-Aug-13 20:01 
AnswerRe: UsbLibrary in WPF application Pin
candude11-Apr-14 5:14
candude11-Apr-14 5:14 
QuestionLocking the USB Barcode Scanner Input Pin
Pasan Eeriyagama2-Jun-13 19:29
Pasan Eeriyagama2-Jun-13 19:29 
QuestionUsbLibrary.UsbHidPort Pin
kainraz27-May-13 7:57
kainraz27-May-13 7:57 
GeneralMy vote of 5 Pin
Wolf_124-Apr-13 19:50
Wolf_124-Apr-13 19:50 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.