Quantcast
Channel: VBForums - Visual Basic .NET
Viewing all articles
Browse latest Browse all 27348

Some closehandle errors

$
0
0
Hi folks,

I use some unmanaged code like CreateFile for accesing a USB device. Now when I started to make clean :) using CloseHandle (btw. this is recommended on msdn to clear after CreateFile) the problems appeared. For instance when I close the form in IDE, many times appear some error message:

System.Runtime.InteropServices.SEHException -> {"External component has thrown an exception."}

with code

0x80004005 which I read is someking of E_FAIL

This is happening in IDE but I don't know if app is working well. There are no visible crashes but I'm not to good to figure if I have to worry or not.
How should I catch this? My dll import declarations are

Code:

    <DllImport("kernel32.dll",
            SetLastError:=True,
            CharSet:=CharSet.Auto)> _
    Private Shared Function CreateFile(ByVal lpFileName As String,
                                      ByVal dwDesiredAccess As Int32,
                                      ByVal dwShareMode As UInt32,
                                      ByVal lpSecurityAttributes As IntPtr,
                                      ByVal dwCreationDisposition As UInt32,
                                      ByVal dwFlagsAndAttributes As UInt32,
                                      ByVal hTemplateFile As IntPtr) As SafeFileHandle
    End Function

    <DllImport("kernel32.dll",
        CharSet:=CharSet.Auto,
        SetLasterror:=True)>
    Public Shared Function CloseHandle(ByVal Handle As Integer) As <MarshalAs(UnmanagedType.Bool)> Boolean
    End Function

and appears to work fine. The problem appeared when I tried to make clean in some Disconnect function:

Code:

  Public Sub Disconnect()

        If hWinUSBInterface = INVALID_HANDLE_VALUE And hDevice = INVALID_HANDLE_VALUE Then

            If Not tmrAutoConnect.Enabled Then
                RaiseEvent Notify(2, "Not connected")
            End If
            Return
        End If

        If hWinUSBInterface <> INVALID_HANDLE_VALUE Then
            WinUsb_Free(hWinUSBInterface)
            hWinUSBInterface = INVALID_HANDLE_VALUE
        End If

' this is the part who cause abnormal behavior
        If hDevice <> INVALID_HANDLE_VALUE Then

            If CloseHandle(hDevice) Then
                hDevice = INVALID_HANDLE_VALUE
                RaiseEvent Disconnected()
            Else
                Dim ErrorStatus As Integer = Err.LastDllError
                RaiseEvent Error(1, ErrorStatus, "Disconnect")
            End If

        End If




    End Sub

Thanks in advance,

Viewing all articles
Browse latest Browse all 27348

Trending Articles