Detect USB device connection

I don't know if it's any help, but this will check for a Pocket PC connection...
Visual Basic:
Imports System.Runtime.InteropServices

'The following class will attempt to determine whether or not a PDA is connected to
'the current PC...
Public Class PDA

    'Constant required by external DLLs...
    Private Const E_FAIL = &H80004005
    Private Const WAIT_FAILED = &HFFFFFFFF
    Private Const WAIT_TIMEOUT = &H102

    <StructLayout(LayoutKind.Sequential)> _
    Private Structure RAPIINIT
        Dim cbSize As Integer
        Dim heRapiInit As Integer
        Dim hrRapiInit As Integer
    End Structure

    'Define the external DLLs...
    'Connection wait...
    <System.Runtime.InteropServices.DllImport("kernel32.dll", SetLastError:=True)> _
       Private Shared Function WaitForSingleObject(ByVal hHandle As Integer, ByVal dwMilliseconds As Integer) As Integer
    End Function

    'Windows CE initialisation...
    <DllImport("rapi.dll", CharSet:=CharSet.Unicode)> _
    Private Shared Function CeRapiInitEx(<MarshalAs(UnmanagedType.Struct)> ByRef prapiinit As RAPIINIT) As Integer
    End Function

    'Windows CE uninitialisation...
    <DllImport("rapi.dll", CharSet:=CharSet.Unicode)> _
    Private Shared Function CeRapiUninit() As Integer
    End Function

    'Determine whether connected...
    Friend Function IsDeviceConnected(Optional ByVal MilliSecondsToWait As Integer = 1000) As Boolean

        Dim ErrorMessg As String

        Try 'Error handler

            Dim rapiStructure As New RAPIINIT
            Dim hresult As Integer

            rapiStructure.cbSize = 12
            hresult = CeRapiInitEx(rapiStructure)
            ErrorMessg = "NoError"

            'Determine failure (no connection)...
            If hresult = E_FAIL Then
                ErrorMessg = "Unable to initialize connection to device !!"
                Return False
            End If

            'Attempt to determine whether the object is available...
            Dim hWait As Integer = WaitForSingleObject(rapiStructure.heRapiInit, MilliSecondsToWait)
            Call CeRapiUninit()
            If hWait = WAIT_FAILED Then
                ErrorMessg = "Unable to wait for device: " & System.Runtime.InteropServices.Marshal.GetLastWin32Error().ToString()
                Return False
            ElseIf (hWait = WAIT_TIMEOUT) Then
                ErrorMessg = "Please check for device connection!!"
                Return False
            ElseIf (rapiStructure.hrRapiInit = E_FAIL) Then
                ErrorMessg = "Failed to connect to device !!"
                Return False
            End If

        Catch ex As Exception
            MsgBox("Not able to connect to PDA" & vbCrLf & "Possible Error :" & ErrorMessg & vbCrLf & "Error :" & ex.Message)
        End Try

        Return True

    End Function

End Class
PS: This isn't my code - I got it off the net somewhere.


Paul.
 
Back
Top