简体   繁体   中英

Reading data from USB using C#?

I do not want to read serial port nor other possible easy shortcuts please. I would like to know how to read a USB port in my laptop using C#. whether you can suggest a site or explain the flow of the process i will greatly appreciate your help

If you want to do development for USB, Jan Axelson's (the author of USB Complete) website is usually a good place to start.

Edit: Assuming it's a HID you want to communicate with this article could be useful and includes C# samples.

The assumption here is that you want to read data on Windows. Here is a code sample:

    public override async Task<byte[]> ReadAsync()
    {
        return await Task.Run(() =>
        {
            var bytes = new byte[ReadBufferSize];
            //TODO: Allow for different interfaces and pipes...
            var isSuccess = WinUsbApiCalls.WinUsb_ReadPipe(_DefaultUsbInterface.Handle, _DefaultUsbInterface.ReadPipe.WINUSB_PIPE_INFORMATION.PipeId, bytes, ReadBufferSize, out var bytesRead, IntPtr.Zero);
            HandleError(isSuccess, "Couldn't read data");
            Tracer?.Trace(false, bytes);
            return bytes;
        });
    }

    [DllImport("winusb.dll", SetLastError = true)]
    public static extern bool WinUsb_ReadPipe(SafeFileHandle InterfaceHandle, byte PipeID, byte[] Buffer, uint BufferLength, out uint LengthTransferred, IntPtr Overlapped);

All code and samples (including other platforms) can be found here: https://github.com/MelbourneDeveloper/Device.Net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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