我对 C# 和 Windows 编程还很陌生,我正在尝试在 USB HID 设备之间建立通信。我使用“SetupDiGetDevicexxxxxx”成功获取了设备路径,并使用“CreateFile()”获取句柄。下面是我的代码。
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);
}
获取设备句柄信息后,我调用写入文件函数如下。
Result = WriteFile(HidHandle, outputReportBuffer[], outputReportBuffer.Length, NumberOfBytesWritten, 0);
Outputbuffer 是长度为 8 的字节数组。出于某种原因,我无法写入 USB HID 设备。 “结果”始终为零。任何帮助表示赞赏。另外,谁能告诉我如何验证 HidHandle
是否有效。当我运行该程序时,我得到的是“1124”。
我确实关注了之前关于此类问题的帖子:Cannot communicate successfully with USB HID device using writefile() ,但没有帮助。
下面是create file和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 库,例如 this one
关于C# WriteFile(),无法写入 USB HID 设备,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12673875/