Checking if a COM port Exists

In many programs, there is an option for selecting the serial port. Instead of providing selection for all possible ports and building an error handling routine for those non-existed in hardware, here is an easy way to enumerate the serial ports of a computer, using Visual Basic 5 or higher (I am not sure about the older versions). It works on both Win95-98 and Win NT 4.


option Explicit
'*************************************************************
' Module         : EnumPorts
' FileName       : EnumPorts.BAS
' Author         : Dimitrios Papadopoulos
' date Created   : 10/08/00 22:07:10
'
' Copyright      : 2000, Dimitrios Papadopoulos.
'                  All Rights Reserved.
'
' Description    : Enumerates Existance of COM Ports
'
' Change History :
' 1.0       10 August 2000
'           Dimitrios Papadopoulos
'           Initial Version
'
'*************************************************************
Type DCB
    DCBlength as Long
    BaudRate as Long
    fBitFields as Long
    wReserved as Integer
    XonLim as Integer
    XoffLim as Integer
    ByteSize as Byte
    Parity as Byte
    StopBits as Byte
    XonChar as Byte
    XoffChar as Byte
    ErrorChar as Byte
    EofChar as Byte
    EvtChar as Byte
    wReserved1 as Integer
End Type

Type COMMCONFIG
    dwSize as Long
    wVersion as Integer
    wReserved as Integer
    dcbx as DCB
    dwProviderSubType as Long
    dwProviderOffset as Long
    dwProviderSize as Long
    wcProviderData as Byte
End Type
'
Declare Function GetDefaultCommConfig Lib "kernel32" _
    Alias "GetDefaultCommConfigA" (byval lpszName as string, _
             lpCC as COMMCONFIG, lpdwSize as Long) as Long
'
public Function EnumSerPorts(port as Integer) as Long
    'this function returns non-zero value if the port exists
    Dim cc as COMMCONFIG, ccsize as Long
'
    ccsize = LenB(cc)     'gets the size of COMMCONFIG structure
'
    EnumSerPorts = GetDefaultCommConfig("COM" + Trim(Str(port)) + _
                                        Chr(0), cc, ccsize)
'
End Function