Reputation: 21
I am using CreateFile
function to create HID Device Handle. Below is sample code. After executing the code, I am always getting HidHandle value -1
, which it should not be. Any suggestions please.
public int CreateFile(string FileName)
{
HidHandle = CreateFile(FileName,GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,0,OPEN_EXISTING,0,0);
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
uint lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
uint hTemplateFile
);
Calling GetLastWin32Error()
returns the value 5
.
Upvotes: 1
Views: 8196
Reputation: 43
CreateFile is not an exported function from kernel32.dll kernel32.dll exports either CreateFileW or CreateFileA
You should use
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int CreateFileW(
[MarshalAs(UnmanagedType.LPWStr)] string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile
);
Upvotes: 0
Reputation: 2521
try changing that to
public int CreateFile(string FileName)
{
return CreateFile(FileName,GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,0,OPEN_EXISTING,0,0);
}
Upvotes: 1
Reputation: 612993
CreateFile
is returning INVALID_HANDLE_VALUE
which indicates failure. You then call GetLastWin32Error()
which returns 5. This is ERROR_ACCESS_DENIED
. In other words, your process does not have sufficient rights to open that file.
Upvotes: 4