简体   繁体   中英

C# WriteFile(), unable to write to USB HID device

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)  

您可能必须使用USB库,像这样的一个

I am sure there is some reason why you are dipping into such low level Win32 functions, but I would advise if you just want to write a file somewhere just use the File class within .net.

If you are just wanting to write bytes then one of the simplest ways is to use File.WriteAllBytes() method.

http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM