I am fairly new to C# as well as windows programming and I am attempting to establish communication between a USB HID device. I got the device path successfully using 'SetupDiGetDevicexxxxxx' and used 'CreateFile()' to get Handle. Below is my code.
public const uint FILE_SHARE_READ = 0x00000001;
public const uint FILE_SHARE_WRITE = 0x00000002;
public const int OPEN_EXISTING = 3;
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
CreateFile(string Devicepath)
{
HidHandle = CreateFile(Devicepath, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
}
After obtaining Device handle info, I am calling write file functions as below.
Result = WriteFile(HidHandle, outputReportBuffer[], outputReportBuffer.Length, NumberOfBytesWritten, 0);
Outputbuffer is the byte array of length 8. For some reason, I was not able to write to USB HID device. "Result" is always zero. Any Help is appreciated. Also, can any one tell me how to verify that HidHandle
is a valid or not. When I run the program I am getting it as "1124".
I did followed previous post on this type of question: Cannot communicate successfully with USB HID device using writefile(), but no help.
Below are the two menthods for create file and writefile.
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, uint lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, uint hTemplateFile );
[DllImport("kernel32.dll")]
static public extern bool WriteFile(int hFile, byte lpBuffer, int nNumberOfBytesToWrite, int lpNumberOfBytesWritten, int lpOverlapped)
Best Answer
You'll probably have to use a USB library, like this one