
CreateFile API Return INVALID_HANDLE_VALUE
Dier,
I was having problems with CreateFile API in Windows 98. I found that in
order to make the API work under windows 98 I had to pass a zero instead
of a SECURITY_ATTRIBUTES structure, and therefore, declare the parameter
as ByVal and long.
On the other hand, under windows 2000, you can pass a
SECURITY_ATTRIBUTES structure, and it will work. In addition, you can
also declare the securityattributes parameters as ByVal and as long
(same as Win98,) and it also works.
Ernesto
PS: You can run the following code in the two different OS, and you will
see that it does not work under win98.
Public Type SECURITY_ATTRIBUTES
nLength As Long
lpSecurityDescriptor As Long
bInheritHandle As Long
End Type
Public Declare Function CreateFile Lib "kernel32" Alias "CreateFileA"
(ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal
dwShareMode As Long, lpSecurityAttributes As SECURITY_ATTRIBUTES, ByVal
dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal
hTemplateFile As Long) As Long
Public Declare Function GetLastError Lib "kernel32" () As Long
Private Sub Command1_Click()
Dim sSecAtb As SECURITY_ATTRIBUTES
Dim lngFilHdl As Long
Dim lngErrNo As Long
Dim strFilPath As String
Dim lMaxPathLength As Integer
strFilPath = "c:\text.txt"
lMaxPathLength = 254
Do While Len(strFilPath) < lMaxPathLength - 1
strFilPath = strFilPath & " "
Loop
strFilPath = Mid$(strFilPath, 1, lMaxPathLength - 1)
strFilPath = strFilPath & Chr$(0)
lngFilHdl = CreateFile(strFilPath, GENERIC_READ, 0, sSecAtb,
CREATE_ALWAYS, FILE_FLAG_RANDOM_ACCESS, 0)
lngErrNo = GetLastError()
Debug.Print
Debug.Print "------"; Now; "------"
Debug.Print "lngFilHdl = "; lngFilHdl
Debug.Print "lngErrNo = "; lngErrNo
End Sub