Hello Jan,
I found your example GenericHid C# program to be most helpful in writing host software in dot.net (everything I have done in the past on the PC side was written in VB6). One thing that was not supported in GenericHID that I wanted to be able to do is to read the indexed string descriptors (Vendor Name, Serial Number etc.). I have added this to GenericHid and as a way of saying thanks I am posting how I did it in case anyone else needs to do the same.
First you have to add the following code to the HidDeclarations.cs file
[ DllImport( "hid.dll", SetLastError=true ) ]
internal static extern Boolean HidD_GetIndexedString(SafeFileHandle HidDeviceObject, Int32 StringIdex, Byte[] StringBuffer, Int32 StringBufferLength );
Next add a function to the Hid.cs file to handle the API call. The line "using System.Text;" is required to use the Encoding function which I used to convert the C unicode string returned by the API call into a C# string.
using System.Text;
internal Boolean GetIndexedString(SafeFileHandle hidHandle, Int32 StringIndex, ref string Destination, Int32 MaxLength)
{
Boolean success;
Byte[] Buffer;
Buffer = new Byte[MaxLength * 2];
try
{
// ***
// API function: HidD_GetIndexedString
// Attempts to read a requested indexed string from the device.
// Requires:
// A handle to a HID
// The index to the string
// A pointer to a string to store the response in
// The max length of string you are willing to accept
// Returns: true on success, false on failure.
// ***
success = HidD_GetIndexedString(hidHandle, StringIndex, Buffer, Buffer.Length);
if (success == true)
{
Destination = Encoding.Unicode.GetString(Buffer);
}
else
{
Destination = null;
}
}
catch (Exception ex)
{
DisplayException(MODULE_NAME, ex);
throw;
}
}
Finally here is an example that uses the GetIndexedString function to read the Vendor Name String (Index = 1) and store it to a text box.
private void cmdGetStringbtn_Click(object sender, EventArgs e)
{
Boolean success = false;
string Result = null;
Int32 Index = 1;
Int32 MaxLength = 20;
success = MyHid.GetIndexedString(hidHandle, Index, ref Result, MaxLength);
if (success == true)
{
IndexedStringtxb.Text = Result;
}
}
Thanks very much for the help you given me in the past Jan. I used your first edition "USB Complete" while I was developing my first USB devices back in 2000 and found it to be very helpful also. I am just getting my feet wet in the C# world (I am primarily an embedded developer), but so far I really like it.