I have to use CreateFile imported from kernel32.dll in some VB .NET project to obtain some handle for WinUSB further functions.
The question is do I need to destroy somehow/something after CreateFile when I don’t need the handle anymore?
The second question is I use WinUsb_Initialize() with CreateFile returned handle to obtain another handle for WinUSB purposes. Do I need to make some cleaning too?
Thanks in advance,
<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
Now I read somewhere if I use safehandlers in CreateFile there is no need to CloseHandle.
This is my “Disconnect” code
Dim ErrorStatus As Integer = 0
If hWinUSBInterface <> INVALID_HANDLE_VALUE Then
WinUsb_Free(hWinUSBInterface)
hWinUSBInterface = INVALID_HANDLE_VALUE
End If
If hDevice <> INVALID_HANDLE_VALUE Then
'hDevice = INVALID_HANDLE_VALUE
'RaiseEvent Error(ErrorStatus, "Disconnect")
If CloseHandle(hDevice) Then
hDevice = INVALID_HANDLE_VALUE
RaiseEvent Disconnected()
Else
ErrorStatus = Err.LastDllError
RaiseEvent Error(ErrorStatus, "Disconnect")
End If
End If
The
HANDLEyou obtained fromCreateFile()must be released by pinvokingCloseHandle().The
WINUSB_INTERFACE_HANDLEyou obtained fromWinUSB_Initialize()must be released by pinvokingWinUSB_Free().Note that these requirements are spelled out in detail in the MSDN Library articles for these functions.