HID Scanner - CreateFile gives Access Denied

0

Using the below code I get error 5 (access denied) when trying to use CreateFile to read my scanner (which is a HID device). In this post someone suggests keyboards are opened in exclusive mode and this is not possible. I've seen other posts of people saying they aren't experiencing such issues.

Should it be possible? Is there something wrong with the parameters?

To the downvoters, please could you tell me whats wrong in your opinion as I'm new to this.

Ps. I've had some success intercepting raw data using User32.dll and the GetRawxxx methods but that isn't a long term solution.

public class Hid
{
    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;

    string DeviceId = "...";

    private SafeFileHandle _ReadSafeFileHandle;
    private FileStream _ReadFileStream;
    private const int ReadBufferSize = 65;

    public async Task<string> Read()
    {
        _ReadSafeFileHandle = CreateFile(DeviceId, GENERIC_READ, FILE_SHARE_READ, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

        if (_ReadSafeFileHandle.IsInvalid) 
            return "Invalid handle " + Marshal.GetLastWin32Error();

        _ReadFileStream = new FileStream(_ReadSafeFileHandle, FileAccess.ReadWrite, ReadBufferSize, false);
        var bytes = new byte[ReadBufferSize];
        await _ReadFileStream.ReadAsync(bytes, 0, bytes.Length);

        return System.Text.ASCIIEncoding.ASCII.GetString(bytes);
    }

    [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);
}

Update:

Tried changing to...

        _CreateFile(DeviceId, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);

I get a valid file handle but calling ReadFile just returns empty buffer. Trying to create a FileStream gives "Access to path denied".

c#
hid
kernel32
asked on Stack Overflow Jun 14, 2019 by TedTrippin • edited Jun 14, 2019 by TedTrippin

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0