D. Edward Mitchell 16:00, 14 April 2020 (UTC) Hello World!    groupKOS Developer Share —usually UNDER CONSTRUCTION

Notes on VB6 com port coding

From groupKOS Developer Share
Jump to navigation Jump to search


VB6.0 module code (portAPI.bas)

' Ref: https://www.developerfusion.com/article/21/com-ports-and-the-mscomm-control/2/

Option Explicit

' API Declarations
Public Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" ( _
                            ByVal lpFileName As String, _
                            ByVal dwDesiredAccess As Long, _
                            ByVal dwShareMode As Long, _
                            lpSecurityAttributes As SECURITY_ATTRIBUTES, _
                            ByVal dwCreationDisposition As Long, _
                            ByVal dwFlagsAndAttributes As Long, _
                            ByVal hTemplateFile As Long) As Long
                            
Public Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

' API Structures
Public Type SECURITY_ATTRIBUTES
    nLength As Long
    lpSecurityDescriptor As Long
    bInheritHandle As Long
End Type

' API constants
Public Const FILE_SHARE_READ = &H1
Public Const FILE_SHARE_WRITE = &H2
Public Const OPEN_EXISTING = 3
Public Const FILE_ATTRIBUTE_NORMAL = &H80
 

' Return TRUE if the COM exists, FALSE if the COM does not exist
Public Function COMAvailable(COMNum As Integer) As Boolean
    Dim hCOM As Long
    Dim ret As Long
    Dim sec As SECURITY_ATTRIBUTES

    ' try to open the COM port
    hCOM = CreateFile("\.\COM" & COMNum & "", 0, FILE_SHARE_READ + _
        FILE_SHARE_WRITE, sec, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
    If hCOM = -1 Then
        COMAvailable = False
    Else
        COMAvailable = True
        ' close the COM port
        ret = CloseHandle(hCOM)
    End If
End Function


VB 6.0 form code with a combo box (cboComm)

Option Explicit

' Ref: https://www.developerfusion.com/article/21/com-ports-and-the-mscomm-control/2/
' Ref: https://www.developerfusion.com/article/21/com-ports-and-the-mscomm-control/4/
' Ref: https://aticleworld.com/serial-port-programming-using-win32-api/

Private Sub ListComPorts()
    Dim i As Integer
    
    cboComm.Clear
    For i = 1 To 16
        If COMAvailable(i) Then
            cboComm.AddItem i
        End If
    Next
    cboComm.ListIndex = 0
End Sub

Private Sub Form_Load()
    ListComPorts    
End Sub