简体   繁体   English

C#WriteFile(),无法写入USB HID设备

[英]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. 我对C#和Windows编程还很陌生,我正在尝试在USB HID设备之间建立通信。 I got the device path successfully using 'SetupDiGetDevicexxxxxx' and used 'CreateFile()' to get Handle. 我使用'SetupDiGetDevicexxxxxx'成功获取了设备路径,并使用'CreateFile()'获取了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. Outputbuffer是长度为8的字节数组。由于某种原因,我无法写入USB HID设备。 "Result" is always zero. “结果”始终为零。 Any Help is appreciated. 任何帮助表示赞赏。 Also, can any one tell me how to verify that HidHandle is a valid or not. 另外,任何人都可以告诉我如何验证HidHandle是否有效。 When I run the program I am getting it as "1124". 当我运行程序时,将其显示为“ 1124”。

I did followed previous post on this type of question: Cannot communicate successfully with USB HID device using writefile() , but no help. 我确实关注了上一篇关于此类问题的文章: 无法使用writefile()与USB HID设备成功通信 ,但没有帮助。

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. 我确定有某些原因会导致您陷入如此低级的Win32函数,但是我建议您是否只想在.net中使用File类来编写文件。

If you are just wanting to write bytes then one of the simplest ways is to use File.WriteAllBytes() method. 如果您只想写字节,那么最简单的方法之一就是使用File.WriteAllBytes()方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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