我找到了解决方案,但我对此并不满意。它似乎与时间有关。这与权限无关。
我将一个 USB HID 数据包写入我的设备,然后读取一个响应数据包。
在 Visual Studio 之外运行 .exe 时,它以某种方式认为在发送写入数据包后立即有响应。
如果我说:
System.Threading.Thread.Sleep(1)
在写入数据包命令和读取数据包命令之间,它的功能就像在 Visual Studio 中一样。
这足以让任何人猜测根本原因吗?
编写报告代码:
var success = Kernel32.WriteFile(
deviceInformation.WriteHandle,
outputReportBuffer,
outputReportBuffer.Length,
ref numberOfBytesWritten,
IntPtr.Zero);
Debug.WriteLine(success ?"usbGenericHidCommunication:writeReportToDevice(): -> Write report succeeded"
: "usbGenericHidCommunication:writeReportToDevice(): -> Write report failed!");
读取报告代码:
nonManagedBuffer = Marshal.AllocHGlobal(inputReportBuffer.Length);
nonManagedOverlapped = Marshal.AllocHGlobal(Marshal.SizeOf(hidOverlapped));
Marshal.StructureToPtr(hidOverlapped, nonManagedOverlapped, false);
// Read the input report buffer
Debug.WriteLine("usbGenericHidCommunication:readReportFromDevice(): -> Attempting to ReadFile");
success = Kernel32.ReadFile(
deviceInformation.ReadHandle,
nonManagedBuffer,
inputReportBuffer.Length,
ref numberOfBytesRead,
nonManagedOverlapped);
if (!success)
{
// We are now waiting for the FileRead to complete
Debug.WriteLine(
"usbGenericHidCommunication:readReportFromDevice(): -> ReadFile started, waiting for completion...");
// Wait a maximum of 3 seconds for the FileRead to complete
var result = Kernel32.WaitForSingleObject(eventObject, 3000);
switch (result)
{
// Has the ReadFile completed successfully?
case Constants.WaitObject0:
// Get the number of bytes transferred
Kernel32.GetOverlappedResult(deviceInformation.ReadHandle, nonManagedOverlapped, ref numberOfBytesRead, false);
Debug.WriteLine("usbGenericHidCommunication:readReportFromDevice(): -> ReadFile successful (overlapped) {0} bytes read", numberOfBytesRead);
break;
// Did the FileRead operation timeout?
case Constants.WaitTimeout:
// Cancel the ReadFile operation
Kernel32.CancelIo(deviceInformation.ReadHandle);