Release or Debug Problem with WriteFile API

Hello,

i wrote a programm which can help to send packets to my USB device

but when i try to use the method WriteFile (in sub sendpacket(startsessionpacket)) i get the win 32 error (Error Invalid Handle)

howewer work hDevice=createFile (...) great!

so what's wrong with my code please Help Me

Option Strict On

Imports System.Runtime.InteropServices

Public Module DeviceIo

Dim theDevInfo As IntPtr

Dim hDevice As IntPtr

Dim usb_packet_size As Integer

Dim deviceioResult As Boolean

Dim thePacket() As Byte

Dim write As Boolean = True

Dim SetupDiGetDeviceInterfaceDetailVar As Boolean = True

#Region "Methodes"

Public Function main() As Boolean

init()

If theDevInfo = IntPtr.Zero Then

MsgBox("communication failed")

Return False

ElseIf Not write Then

MsgBox("WriteFile failed")

Return False

ElseIf SetupDiGetDeviceInterfaceDetailVar = False Then

MsgBox("SetupDiGetDeviceInterfaceDetail failed")

Else

Dim theProduktPacket() As Byte = New Byte() _

{&H14, &H0, &H0, &H0, &HFE, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

'send the product packet

SendPacket(theProduktPacket)

'receive the product informations

Do

thePacket = GetPacket()

If thePacket(0) = 20 And thePacket(4) = BasicPacketIDs.Pid_Product_Data Then Exit Do

Loop

Return True

End If

End Function

Private Function ToPosition(ByVal degree As Double) As Integer

Return CInt(degree * (2 ^ 31) / 180)

End Function

Public Sub init()

Dim thePacket2() As Byte

Dim theStartSessionPacket() As Byte

theStartSessionPacket = New Byte() _

{&H0, &H0, &H0, &H0, &H5, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

Dim GUID_DEVINTERFACE_GRMNUSB As System.Guid

Dim DIDI As SP_DEVICE_INTERFACE_DATA

Dim DIDC As SP_DEVINFO_DATA

Dim DIDID As SP_DEVICE_INTERFACE_DETAIL_DATA

Dim len As Integer

Dim ip As IntPtr

Dim bytes As Byte() = Nothing

Dim devicePath As String = vbNullString

DIDI.cbSize = Marshal.SizeOf(DIDI)

DIDC.cbSize = Marshal.SizeOf(DIDC)

GUID_DEVINTERFACE_GRMNUSB = New System.Guid("2C9C45C2-8E7D-4C08-A12D-816BBAE722C0")

theDevInfo = SetupDiGetClassDevs(GUID_DEVINTERFACE_GRMNUSB, vbNullString, IntPtr.Zero, DIGCF_DEVICEINTERFACE Or DIGCF_PRESENT)

If Not SetupDiEnumDeviceInterfaces(theDevInfo, IntPtr.Zero, GUID_DEVINTERFACE_GRMNUSB, 0, DIDI) Then

theDevInfo = Nothing

Return

End If

DIDID = New SP_DEVICE_INTERFACE_DETAIL_DATA

DIDID.cbSize = 6 'Marshal.SizeOf(DIDID)

If Not SetupDiGetDeviceInterfaceDetail(theDevInfo, DIDI, IntPtr.Zero, 0, len, IntPtr.Zero) Then

ip = Marshal.AllocHGlobal(len)

Marshal.StructureToPtr(DIDID, ip, True)

If SetupDiGetDeviceInterfaceDetail(theDevInfo, DIDI, ip, len, len, IntPtr.Zero) Then

bytes = New Byte(len - 1) {}

Marshal.Copy(ip, bytes, 0, len)

devicePath = System.Text.Encoding.Unicode.GetString(bytes, 4, bytes.Length - 4)

Else

SetupDiGetDeviceInterfaceDetailVar = False

Return

End If

End If

Dim usbpacketsize As IntPtr

usbpacketsize = Marshal.AllocHGlobal(4)

Dim theBytesReturned As Integer

hDevice = CreateFile(devicePath, GENERIC_READ Or GENERIC_WRITE, _

0, IntPtr.Zero, IO.FileMode.Open, &H80, IntPtr.Zero)

If (hDevice.Equals(-1) Or hDevice = IntPtr.Zero) Then

DisplayLastWin32Error()

Return

End If

MsgBox(hDevice)

'Get the USB packet size, which we need for sending packets

If DeviceIoControl(hDevice, IOCTL_USB_PACKET_SIZE, IntPtr.Zero, 0, usbpacketsize, 4, theBytesReturned, IntPtr.Zero) Then

If theBytesReturned > 0 Then

Dim bytesTemp() As Byte

bytesTemp = New Byte(theBytesReturned - 1) {}

Marshal.Copy(usbpacketsize, bytesTemp, 0, theBytesReturned)

If theBytesReturned = 2 Then

usb_packet_size = BitConverter.ToInt16(bytesTemp, 0)

End If

End If

Else

Marshal.FreeHGlobal(ip)

Return

End If

'send the startsessionpacket

SendPacket(theStartSessionPacket)

If Not write Then

Return

End If

'get the ok from the device

Do

thePacket2 = GetPacket()

If thePacket2(0) = 0 And thePacket2(4) = USBProtocolPacketID.Pid_Session_Started Then Exit Do

Loop

End Sub

Public Function GetPacket() As Byte()

Dim theNewBuffer As List(Of Byte)

Dim bufferSize As Integer

Dim theTempBuffer As Byte()

Dim theBytesReturned As Integer

theNewBuffer = New List(Of Byte)

Do

theTempBuffer = New Byte(ASYNC_DATA_SIZE - 1) {}

DeviceIoControl(hDevice, IOCTL_ASYNC_IN, IntPtr.Zero, 0, theTempBuffer, ASYNC_DATA_SIZE, theBytesReturned, IntPtr.Zero)

bufferSize += theBytesReturned

theNewBuffer.AddRange(New List(Of Byte)(theTempBuffer).GetRange(0, theBytesReturned))

If theBytesReturned < ASYNC_DATA_SIZE Then Exit Do

Loop

If theNewBuffer.Count > 0 Then

If theTempBuffer(0) = 0 And theTempBuffer(4) = 2 Then

' DataAvailable ...

theTempBuffer = New Byte(MAX_BUFFER_SIZE - 1) {}

theBytesReturned = 0

ReadFile(hDevice, theTempBuffer, MAX_BUFFER_SIZE, theBytesReturned, IntPtr.Zero)

If theBytesReturned > 0 Then

theNewBuffer = New List(Of Byte)(theTempBuffer).GetRange(0, theBytesReturned)

End If

Return theNewBuffer.ToArray

Else

Return theTempBuffer

End If

End If

End Function

Public Sub SendPacket(ByVal aPacket As Byte())

Dim theBytesReturned As Integer

If Not WriteFile(hDevice, aPacket, aPacket.Length, theBytesReturned, Nothing) Then

DisplayLastWin32Error()

write = False

Return

End If

'If the packet size was an exact multiple of the USB packet

'size, we must make a final write call with no data

If usb_packet_size <> 0 Then

If (aPacket.Length Mod usb_packet_size = 0) Then

Dim newBytes() As Byte = New Byte() {}

If Not WriteFile(hDevice, newBytes, 0, theBytesReturned, IntPtr.Zero) Then

DisplayLastWin32Error()

End If

End If

End If

End Sub

#End Region




Answer this question

Release or Debug Problem with WriteFile API

  • 3D Paul

    here are the declarations

    Imports System.Runtime.InteropServices

    Module Win32Methods

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _

    Public Structure SP_DEVINFO_DATA

    Public cbSize As Integer

    Public ClassGuid As Guid

    Public DevInst As UInteger

    Public Reserved As IntPtr

    End Structure

    <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _

    Public Structure SP_DEVICE_INTERFACE_DATA

    Public cbSize As Integer

    Public InterfaceClassGuid As Guid

    Public Flags As Integer

    Public Reserved As IntPtr

    End Structure

    <StructLayout(LayoutKind.Sequential, Pack:=1)> _

    Public Class SP_DEVICE_INTERFACE_DETAIL_DATA

    Public cbSize As Integer

    <MarshalAs(UnmanagedType.LPWStr)> Public DevicePath As String

    End Class

    Public Enum DeviceType As Integer

    FILE_DEVICE_BEEP = &H1

    FILE_DEVICE_CD_ROM = &H2

    FILE_DEVICE_CD_ROM_FILE_SYSTEM = &H3

    FILE_DEVICE_CONTROLLER = &H4

    FILE_DEVICE_DATALINK = &H5

    FILE_DEVICE_DFS = &H6

    FILE_DEVICE_DISK = &H7

    FILE_DEVICE_DISK_FILE_SYSTEM = &H8

    FILE_DEVICE_FILE_SYSTEM = &H9

    FILE_DEVICE_INPORT_PORT = &HA

    FILE_DEVICE_KEYBOARD = &HB

    FILE_DEVICE_MAILSLOT = &HC

    FILE_DEVICE_MIDI_IN = &HD

    FILE_DEVICE_MIDI_OUT = &HE

    FILE_DEVICE_MOUSE = &HF

    FILE_DEVICE_MULTI_UNC_PROVIDER = &H10

    FILE_DEVICE_NAMED_PIPE = &H11

    FILE_DEVICE_NETWORK = &H12

    FILE_DEVICE_NETWORK_BROWSER = &H13

    FILE_DEVICE_NETWORK_FILE_SYSTEM = &H14

    FILE_DEVICE_NULL = &H15

    FILE_DEVICE_PARALLEL_PORT = &H16

    FILE_DEVICE_PHYSICAL_NETCARD = &H17

    FILE_DEVICE_PRINTER = &H18

    FILE_DEVICE_SCANNER = &H19

    FILE_DEVICE_SERIAL_MOUSE_PORT = &H1A

    FILE_DEVICE_SERIAL_PORT = &H1B

    FILE_DEVICE_SCREEN = &H1C

    FILE_DEVICE_SOUND = &H1D

    FILE_DEVICE_STREAMS = &H1E

    FILE_DEVICE_TAPE = &H1F

    FILE_DEVICE_TAPE_FILE_SYSTEM = &H20

    FILE_DEVICE_TRANSPORT = &H21

    FILE_DEVICE_UNKNOWN = &H22

    FILE_DEVICE_VIDEO = &H23

    FILE_DEVICE_VIRTUAL_DISK = &H24

    FILE_DEVICE_WAVE_IN = &H25

    FILE_DEVICE_WAVE_OUT = &H26

    FILE_DEVICE_8042_PORT = &H27

    FILE_DEVICE_NETWORK_REDIRECTOR = &H28

    FILE_DEVICE_BATTERY = &H29

    FILE_DEVICE_BUS_EXTENDER = &H2A

    FILE_DEVICE_MODEM = &H2B

    FILE_DEVICE_VDM = &H2C

    FILE_DEVICE_MASS_STORAGE = &H2D

    FILE_DEVICE_SMB = &H2E

    FILE_DEVICE_KS = &H2F

    FILE_DEVICE_CHANGER = &H30

    FILE_DEVICE_SMARTCARD = &H31

    FILE_DEVICE_ACPI = &H32

    FILE_DEVICE_DVD = &H33

    FILE_DEVICE_FULLSCREEN_VIDEO = &H34

    FILE_DEVICE_DFS_FILE_SYSTEM = &H35

    FILE_DEVICE_DFS_VOLUME = &H36

    FILE_DEVICE_SERENUM = &H37

    FILE_DEVICE_TERMSRV = &H38

    FILE_DEVICE_KSEC = &H39

    FILE_DEVICE_FIPS = &H3A

    FILE_DEVICE_INFINIBAND = &H3B

    FILE_DEVICE_VMBUS = &H3E

    FILE_DEVICE_CRYPT_PROVIDER = &H3F

    FILE_DEVICE_WPD = &H40

    FILE_DEVICE_BLUETOOTH = &H41

    End Enum

    Public Enum FileMethod As Integer

    METHOD_BUFFERED = &H0

    METHOD_IN_DIRECT = &H1

    METHOD_OUT_DIRECT = &H2

    METHOD_NEITHER = &H3

    End Enum

    Public Enum FileAccess

    FILE_ANY_ACCESS = &H0

    End Enum

    Public Const DIGCF_PRESENT As Short = &H2S

    Public Const DIGCF_DEVICEINTERFACE As Short = &H10S

    Public Const DIGCF_ALLCLASSES As Short = &H4S

    Public Const DIGCF_PROFILE As Short = &H8S

    Public Const GENERIC_READ As Integer = &H80000000

    Public Const GENERIC_WRITE As Integer = &H40000000

    Public Const MAX_BUFFER_SIZE As Integer = 4096

    Public Const ASYNC_DATA_SIZE As Integer = 64

    Public ReadOnly IOCTL_USB_PACKET_SIZE As Integer = _

    CTL_CODE(DeviceType.FILE_DEVICE_UNKNOWN, &H851, FileMethod.METHOD_BUFFERED, _

    FileAccess.FILE_ANY_ACCESS)

    Public ReadOnly IOCTL_ASYNC_IN As Integer = _

    CTL_CODE(DeviceType.FILE_DEVICE_UNKNOWN, &H850, FileMethod.METHOD_BUFFERED, _

    FileAccess.FILE_ANY_ACCESS)

    Public Declare Auto Function SetupDiGetClassDevs Lib "setupapi.dll" ( _

    ByRef ClassGuid As Guid, _

    <MarshalAs(UnmanagedType.LPTStr)> ByVal Enumerator As String, _

    ByVal hwndParent As IntPtr, _

    ByVal Flags As Integer) As intptr

    Public Declare Auto Function SetupDiEnumDeviceInterfaces Lib "setupapi.dll" _

    (ByVal DeviceInfoSet As intptr, _

    ByVal DeviceInfoData As IntPtr, _

    ByRef ClassGuid As Guid, _

    ByVal MemberIndex As Integer, _

    ByRef DeviceInterfaceData As SP_DEVICE_INTERFACE_DATA) As Boolean

    Public Declare Auto Function SetupDiGetDeviceInterfaceDetail Lib "setupapi.dll" _

    (ByVal DeviceInfoSet As intptr, _

    ByRef DeviceInterfaceData As SP_DEVICE_INTERFACE_DATA, _

    ByRef DeviceInterfaceDetailData As SP_DEVICE_INTERFACE_DETAIL_DATA, _

    ByVal DeviceInterfaceDetailDataSize As Integer, _

    ByRef RequiredSize As Integer, _

    ByRef DeviceInfoData As SP_DEVINFO_DATA) As Boolean

    Public Declare Auto Function SetupDiGetDeviceInterfaceDetail Lib "setupapi.dll" _

    (ByVal DeviceInfoSet As intptr, _

    ByRef DeviceInterfaceData As SP_DEVICE_INTERFACE_DATA, _

    ByVal DeviceInterfaceDetailData As IntPtr, _

    ByVal DeviceInterfaceDetailDataSize As Integer, _

    ByRef RequiredSize As Integer, ByVal DeviceInfoData As IntPtr) As Boolean

    Public Declare Auto Function SetupDiGetDeviceInterfaceDetail Lib "setupapi.dll" _

    (ByVal DeviceInfoSet As intptr, _

    ByRef DeviceInterfaceData As SP_DEVICE_INTERFACE_DATA, _

    ByRef DeviceInterfaceDetailData As Byte(), _

    ByVal DeviceInterfaceDetailDataSize As Integer, _

    ByRef RequiredSize As Integer, _

    ByVal DeviceInfoData As IntPtr) As Boolean

    Public Declare Auto Function CreateFile Lib "kernel32.dll" _

    (ByVal lpFileName As String, _

    ByVal dwDesiredAccess As Integer, _

    ByVal dwShareMode As System.IO.FileShare, _

    ByVal lpSecurityAttributes As IntPtr, _

    ByVal dwCreationDisposition As System.IO.FileMode, _

    ByVal dwFlagsAndAttributes As Integer, _

    ByVal hTemplateFile As IntPtr) As intptr

    Public Declare Auto Function WriteFile Lib "kernel32.dll" _

    (ByVal hFile As IntPtr, _

    ByVal lpBuffer As Byte(), _

    ByVal nNumberOfBytesToWrite As Integer, _

    ByRef lpNumberOfBytesWritten As Integer, _

    ByRef lpOverlapped As IntPtr) As Boolean

    Public Declare Auto Function ReadFile Lib "kernel32.dll" _

    (ByVal hFile As intptr, _

    ByVal lpBuffer As Byte(), _

    ByVal nNumberOfBytesToRead As Integer, _

    ByRef lpNumberOfBytesRead As Integer, _

    ByRef lpOverlapped As IntPtr) As Boolean

    Public Declare Auto Function DeviceIoControl Lib "kernel32.dll" _

    (ByVal hDevice As intptr, _

    ByVal dwIoControlCode As Integer, _

    ByVal lpInBuffer As IntPtr, _

    ByVal nInBufferSize As Integer, _

    ByVal lpOutBuffer As IntPtr, _

    ByVal nOutBufferSize As Integer, _

    ByRef lpBytesReturned As Integer, _

    ByVal lpOverlapped As IntPtr) As Boolean

    Public Declare Auto Function DeviceIoControl Lib "kernel32.dll" _

    (ByVal hDevice As intptr, _

    ByVal dwIoControlCode As Integer, _

    ByVal lpInBuffer As IntPtr, _

    ByVal nInBufferSize As Integer, _

    ByVal lpOutBuffer As Byte(), _

    ByVal nOutBufferSize As Integer, _

    ByRef lpBytesReturned As Integer, _

    ByVal lpOverlapped As IntPtr) As Boolean

    Public Sub DisplayLastWin32Error()

    Dim code As Integer

    Dim ex As System.ComponentModel.Win32Exception

    code = Marshal.GetLastWin32Error

    ex = New System.ComponentModel.Win32Exception(code)

    MsgBox(String.Format("Message: {0}{2}Code: {1}", ex.Message, code, _

    System.Environment.NewLine), MsgBoxStyle.Critical)

    End Sub

    Public Function CTL_CODE(ByVal DeviceType As DeviceType, ByVal [Function] As Integer, _

    ByVal Method As FileMethod, ByVal Access As FileAccess) As Integer

    Return (((DeviceType) << 16) Or ((Access) << 14) Or (([Function]) << 2) Or (Method))

    End Function

    End Module



  • Venkatram

    It is hard for me to tell if there's anything wrong just by looking at the code.

    My suggestion would be to make sure that the PInvoke signatures actually match what the Win32 API expects. Subtle differences such as the one that I pointed out with the marshalling of the Boolean can affect which code gets executed and those usually depend on whatever the memory happens to contain at the time when you call them.

    Also have you verified that you are not getting INVALID_HANDLE from your call to CreateFile You can do this by making sure the IntPtr is not -1.

    Is there any difference if you run your code from VS without Debugging (Ctrl+F5)

    Hope that helps,



  • UserAccountControl

    thanks for your answer

    i changed the return value from writefile from boolean to integer but nothing happened! in the IDE writefile=1 and out writefile=0! however the createfile return a valid handle in the both cases but writefile return the "invalid handle" error out the IDE!

    with Ctrl + F5 the programm failed! it works only with debugging! (dont understand why)

    can we talk through msn this is my email: la_big_1981@beispiel.com

    i don't have a PInvokeStackImbalance so that 's why i think all my declarations are ok right



  • Jeremy Maddrey

    this is a snippset of my code methods sendpackets, init and getpacket

    when i test my programm in the IDE it works great but when i test it out with the .exe file in the release or debug folder the handle to my device is invalid and writefile failed ("error invalid handle")

    i just wonder why!

    Public Declare Auto Function CreateFile Lib "kernel32.dll" _

    (ByVal lpFileName As String, _

    ByVal dwDesiredAccess As Integer, _

    ByVal dwShareMode As Integer, _

    ByVal lpSecurityAttributes As Integer, _

    ByVal dwCreationDisposition As Integer, _

    ByVal dwFlagsAndAttributes As Integer, _

    ByVal hTemplateFile As Integer) As IntPtr

    Public Declare Auto Function WriteFile Lib "kernel32.dll" _

    (ByVal hFile As IntPtr, _

    ByVal lpBuffer As Byte(), _

    ByVal nNumberOfBytesToWrite As Integer, _

    ByRef lpNumberOfBytesWritten As Integer, _

    ByRef lpOverlapped As IntPtr) As Boolean

    Public Sub init()

    Dim thePacket() As Byte

    Dim theStartSessionPacket() As Byte

    theStartSessionPacket = New Byte() _

    {&H0, &H0, &H0, &H0, &H5, &H0, &H0, &H0, &H0, &H0, &H0, &H0}

    Dim GUID_DEVINTERFACE_GRMNUSB As System.Guid

    Dim DIDI As SP_DEVICE_INTERFACE_DATA

    Dim DIDC As SP_DEVINFO_DATA

    Dim DIDID As SP_DEVICE_INTERFACE_DETAIL_DATA

    Dim len As Integer

    Dim ip As IntPtr

    Dim bytes As Byte() = Nothing

    Dim devicePath As String = vbNullString

    DIDI.cbSize = Marshal.SizeOf(DIDI)

    DIDC.cbSize = Marshal.SizeOf(DIDC)

    GUID_DEVINTERFACE_GRMNUSB = New System.Guid("2C9C45C28E7D4C08A12D816BBAE722C0")

    theDevInfo = SetupDiGetClassDevs(GUID_DEVINTERFACE_GRMNUSB, vbNullString, IntPtr.Zero, DIGCF_DEVICEINTERFACE Or DIGCF_PRESENT)

    If Not SetupDiEnumDeviceInterfaces(theDevInfo, IntPtr.Zero, GUID_DEVINTERFACE_GRMNUSB, 0, DIDI) Then

    theDevInfo = Nothing

    Return

    End If

    DIDID = New SP_DEVICE_INTERFACE_DETAIL_DATA

    DIDID.cbSize = 6 'Marshal.SizeOf(DIDID)

    If Not SetupDiGetDeviceInterfaceDetail(theDevInfo, DIDI, IntPtr.Zero, 0, len, IntPtr.Zero) Then

    ip = Marshal.AllocHGlobal(len)

    Marshal.StructureToPtr(DIDID, ip, True)

    If SetupDiGetDeviceInterfaceDetail(theDevInfo, DIDI, ip, len, len, IntPtr.Zero) Then

    bytes = New Byte(len - 1) {}

    Marshal.Copy(ip, bytes, 0, len)

    devicePath = System.Text.Encoding.Unicode.GetString(bytes, 4, bytes.Length - 4)

    Else

    Return

    End If

    End If

    Dim usbpacketsize As IntPtr

    usbpacketsize = Marshal.AllocHGlobal(4)

    Dim theBytesReturned As Integer

    Marshal.FreeHGlobal(hDevice)

    Dim bool As Boolean = CloseHandle(hDevice)

    hDevice = CreateFile(devicePath, GENERIC_READ Or GENERIC_WRITE, _

    0, 0&, OPEN_EXISTING, 0&, 0&)

    'Get the USB packet size, which we need for sending packets

    If DeviceIoControl(hDevice, IOCTL_USB_PACKET_SIZE, IntPtr.Zero, 0, usbpacketsize, 4, theBytesReturned, IntPtr.Zero) Then

    If theBytesReturned > 0 Then

    Dim bytes1() As Byte

    bytes1 = New Byte(theBytesReturned - 1) {}

    Marshal.Copy(usbpacketsize, bytes1, 0, theBytesReturned)

    If theBytesReturned = 2 Then

    usb_packet_size = BitConverter.ToInt16(bytes1, 0)

    End If

    End If

    Else

    Marshal.FreeHGlobal(ip)

    Return

    End If

    'send the startsessionpacket

    SendPacket(theStartSessionPacket)

    'get the ok from the device

    Do

    thePacket = GetPacket()

    If thePacket(0) = 0 And thePacket(4) = USBProtocolPacketID.Pid_Session_Started Then Exit Do

    Loop

    End Sub

    Public Function GetPacket() As Byte()

    Dim buffer As List(Of Byte)

    Dim bufferSize As Integer

    Dim data As Byte()

    Dim dataSize As Integer

    buffer = New List(Of Byte)

    Do

    data = New Byte(ASYNC_DATA_SIZE - 1) {}

    DeviceIoControl(hDevice, IOCTL_ASYNC_IN, IntPtr.Zero, 0, data, ASYNC_DATA_SIZE, dataSize, IntPtr.Zero)

    bufferSize += dataSize

    buffer.AddRange(New List(Of Byte)(data).GetRange(0, dataSize))

    If dataSize < ASYNC_DATA_SIZE Then Exit Do

    Loop

    If buffer.Count > 0 Then

    If data(0) = 0 And data(4) = 2 Then

    ' DataAvailable ...

    data = New Byte(MAX_BUFFER_SIZE - 1) {}

    dataSize = 0

    ReadFile(hDevice, data, MAX_BUFFER_SIZE, dataSize, IntPtr.Zero)

    If dataSize > 0 Then

    buffer = New List(Of Byte)(data).GetRange(0, dataSize)

    Return data

    End If

    Else

    Return data

    End If

    End If

    Return Nothing

    End Function

    Public Sub SendPacket(ByVal aPacket As Byte())

    Dim theBytesReturned As Integer

    Dim bool As Boolean = WriteFile(hDevice, aPacket, aPacket.Length, theBytesReturned, Nothing)

    If Not bool Then

    DisplayLastWin32Error()

    theDevInfo = IntPtr.Zero

    Return

    End If

    'If the packet size was an exact multiple of the USB packet

    'size, we must make a final write call with no data

    If usb_packet_size <> 0 Then

    If (aPacket.Length Mod usb_packet_size = 0) Then

    Dim newBytes() As Byte

    newBytes = New Byte() {}

    WriteFile(hDevice, newBytes, 0, theBytesReturned, IntPtr.Zero)

    End If

    End If

    End Sub

    Public Function getProductID() As String

    'Dim bytesID() As Byte = New Byte() {thePacket(12), thePacket(13)}

    'Dim bytesSVersion() As Byte = New Byte() {thePacket(14), thePacket(15)}

    Dim byteDesc As List(Of Byte)

    byteDesc = New List(Of Byte)(thePacket).GetRange(16, 4080)

    'Dim productID As Integer = BitConverter.ToUInt16(bytesID, 0)

    'Dim productVersion As Short = BitConverter.ToInt16(bytesSVersion, 0)

    Dim resz() As Byte = byteDesc.ToArray

    Dim desc As String = System.Text.Encoding.ASCII.GetString(resz, 0, resz.Length)

    Return desc

    End Function

    #End Region



  • rajabharathi

    I looked at your PInvoke declaration and there is only one minor change that you need to make so that the managed and unmanaged signatures match.

    You should change the return type of the WriteFile function to either be "As Integer", or explicitly state that it is a BOOL type by writing: "<MarshalAs(UnamagedType.Bool)> Boolean"

    I'm not sure that the change in the declaration will address your problem, but otherwise you might get unexpected values when looking at the result of the function.

    Now, to what might actually be the real problem. How are you obtaining the handle that you are passing to the function



  • MarioBR

    i found the solution

    the last argument from writefile should be ByVal and not ByRef



  • Vestas_Jakob&amp;#33;

    Hello,

    i tried to test my programm wrote in Visual Basic 2005 Express and following happened

    - when i compile and test in the IDE (Debug) it works great but (Release) doesn't work 100%

    - when i use the .exe files in debug or release folder both don't work 100%

    this is my code snippset: the problem is writefile , out the IDE after the command writefile i become the win32 error "invalid handle"! i wonder because in the IDE it's not the same error message and there's no error respectively!

    so pleeease help me!

    Public Declare Auto Function WriteFile Lib "kernel32.dll" _

    (ByVal hFile As intptr, _

    ByVal lpBuffer As Byte(), _

    ByVal nNumberOfBytesToWrite As Integer, _

    ByRef lpNumberOfBytesWritten As Integer, _

    ByRef lpOverlapped As IntPtr) As Boolean

    Public Sub SendPacket(ByVal aPacket As Byte())

    Dim theBytesReturned As Integer

    Dim bool As Boolean = WriteFile(hDevice, aPacket, aPacket.Length, theBytesReturned, Nothing)

    //this is the error message ---"invalid handle"--- out the IDE
    DisplayLastWin32Error()

    'If the packet size was an exact multiple of the USB packet

    'size, we must make a final write call with no data

    If usb_packet_size <> 0 Then

    If (aPacket.Length Mod usb_packet_size = 0) Then

    Dim newBytes() As Byte

    newBytes = New Byte() {}

    WriteFile(hDevice, newBytes, 0, theBytesReturned, IntPtr.Zero)

    End If

    End If

    End Sub



  • Release or Debug Problem with WriteFile API