Exemple #1
0
        private HidDeviceData ReadData(int timeout)
        {
            var buffer = new byte[Capabilities.InputReportByteLength];
            var status = HidDeviceData.ReadStatus.NoDataRead;

            if (deviceCapabilities.InputReportByteLength > 0)
            {
                var bytesRead = 0;

                if (deviceReadMode == DeviceMode.Overlapped)
                {
                    var security       = new NativeMethods.SECURITY_ATTRIBUTES();
                    var overlapped     = new NativeMethods.OVERLAPPED();
                    var overlapTimeout = timeout <= 0 ? NativeMethods.WAIT_INFINITE : timeout;

                    security.lpSecurityDescriptor = IntPtr.Zero;
                    security.bInheritHandle       = true;
                    security.nLength = Marshal.SizeOf(security);

                    overlapped.Offset     = 0;
                    overlapped.OffsetHigh = 0;
                    overlapped.hEvent     = NativeMethods.CreateEvent(ref security, Convert.ToInt32(false), Convert.ToInt32(true), string.Empty);

                    try
                    {
                        NativeMethods.ReadFileOverlapped(ReadHandle, ref buffer[0], buffer.Length, ref bytesRead, ref overlapped);

                        var result = NativeMethods.WaitForSingleObject(overlapped.hEvent, overlapTimeout);

                        switch (result)
                        {
                        case NativeMethods.WAIT_OBJECT_0: status = HidDeviceData.ReadStatus.Success; break;

                        case NativeMethods.WAIT_TIMEOUT:
                            status = HidDeviceData.ReadStatus.WaitTimedOut;
                            buffer = new byte[] {};
                            break;

                        case NativeMethods.WAIT_FAILED:
                            status = HidDeviceData.ReadStatus.WaitFail;
                            buffer = new byte[] { };
                            break;

                        default:
                            status = HidDeviceData.ReadStatus.NoDataRead;
                            buffer = new byte[] { };
                            break;
                        }
                    }
                    catch { status = HidDeviceData.ReadStatus.ReadError; }
                }
                else
                {
                    try
                    {
                        NativeMethods.ReadFile(ReadHandle, ref buffer[0], buffer.Length, ref bytesRead, IntPtr.Zero);
                        if (bytesRead > 0)
                        {
                            status = HidDeviceData.ReadStatus.Success;
                        }
                    }
                    catch { status = HidDeviceData.ReadStatus.ReadError; }
                }
            }
            return(new HidDeviceData(buffer, status));
        }