我试图通过尝试读写HID来更改键盘LED的颜色。到目前为止,write方法可以正常工作,并且我能够成功更改键盘颜色,但是,每当我尝试从中读取键盘颜色以获取设备状态时,它将引发错误代码87,并且DeviceIOControl方法返回false。我实际上是通过PInvoke使用Kernel32.dll的方法,并且此代码对于在C ++中进行读写都可以正常工作,但是我似乎无法在C#中读取它。
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern SafeFileHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool DeviceIoControl(
SafeFileHandle hDevice,
uint IoControlCode,
[MarshalAs(UnmanagedType.AsAny)]
[In] object InBuffer,
uint nInBufferSize,
[MarshalAs(UnmanagedType.AsAny)]
[Out] object OutBuffer,
uint nOutBufferSize,
ref uint pBytesReturned,
[In] IntPtr Overlapped
);
public void initialize(){
devHandle = CreateFile(path, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
if (devHandle == null) {
isInitialized = false;
return false;
}
isInitialized = true;
return true;
}
public void deviceStatus()
{
uint writtenByteLength = 0;
byte[] Buffer = { 0x02, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
bool write = DeviceIoControl(devHandle, 0xb0195, Buffer, (uint)Buffer.Length, IntPtr.Zero, 0, ref writtenByteLength, IntPtr.Zero); //Write method works
Buffer[0] = 0x01;
bool read = DeviceIoControl(devHandle, 0xb01a2, null, 0, Buffer, (uint)Buffer.Length, ref writtenByteLength, IntPtr.Zero); //This returns false and does not work
if (!read) {
Global.logger.Info("Error Code: " + Marshal.GetLastWin32Error());
}
Global.logger.Info("Read Status: " + write + ": " + read);
Global.logger.Info("Read Bytes: " + Buffer[0] + ": " + Buffer[1]);
}
由于此代码在C ++中可以正常工作,所以我不知道为什么它返回错误87,这是C#中不正确的参数。因为使用相同的PInvoke可以很好地实现写入方法,所以我能够更改键盘LED的颜色。我尝试过进行从byte []到IntPtr的元帅转换,并将byte []作为IntPtr传递,但这似乎也不起作用。任何帮助将非常感激。谢谢!