Visual Basic System Services
ConfigurePort: Determine Available COM Ports with the MSCOMM Control
     
Posted:   Wednesday June 02, 2004
Updated:   Monday December 26, 2011
     
Applies to:   VB4-32, VB5, VB6
Developed with:   VB6, Windows XP
OS restrictions:   None
Author:   VBnet - Randy Birch
     

Related:  

Using CreateFile to Determine Available COM Port
     
 Prerequisites
None.

The CreateFile version of this code provides developers with the ability to eliminate the MSCOMM control from their application distribution when all that is required is code to determine the COM ports available.

This demo duplicates the CreateFile API demo, substituting MSCOMM controls for all activities. Like the CreateFile method this code also utilizes two key functions.

GetInstalledCOMPorts() passes a series of port numbers (1 through 16 in this demo) to the worker COMCheckPort function, which uses the MSCOMM control to attempt to open the port. If the port is in use the error trap fires, and the function returns False. If the port can be successfully opened, the port is tested by issuing an open and close call, and if both succeed the function returns True indicating the port is available and ready for use. The results of each call are entered to a list indicating which ports are available for use.

GetFirstAvailableCOMPort() also uses COMCheckPort but this routine exits once the first available port has been determined. For demo purposes the result is displayed in the list box as well.

In order to provide the functionality of the API Open COM/Close COM buttons, a second MSCOMM control is required on the form. The code also includes the same ConfigurePort API demo showing how to present the user with Windows' standard dialog to allow customization of the COM port baud rate, bits, parity, stop bits and flow control, as well as restore the default settings.

 BAS Module Code
None.

 Form Code
To a form, add a list box (List1), five command buttons (Command1-Command5), two option buttons (Option1, Option2) and two mscomm controls (MSComm1, MSComm2). Add the following code:

Option Explicit
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Copyright ©1996-2011 VBnet/Randy Birch, All Rights Reserved.
' Some pages may also contain other copyrights by the author.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Distribution: You can freely use this code in your own
'               applications, but you may not reproduce 
'               or publish this code on any web site,
'               online service, or distribute as source 
'               on any media without express permission.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Declare Function ConfigurePort Lib "winspool.drv" _
   Alias "ConfigurePortA" _
  (ByVal pName As Any, _
   ByVal hwnd As Long, _
   ByVal pPortName As String) As Long



Private Sub Form_Load()

   Command1.Caption = "Get Installed COM Ports"
   Command2.Caption = "Get First Available Port (API)"
   Command3.Caption = "Configure Port Dialog"
   Command4.Caption = "Open COM1"
   Command5.Caption = "Close COM1"
   
   Option1.Caption = "COM1:"
   Option2.Caption = "COM2:"
   Option1.Value = True
   
End Sub


Private Sub Form_Unload(Cancel As Integer)

   If MSComm2.PortOpen = True Then
      MSComm2.PortOpen = False
   End If
   
End Sub

Private Sub Command1_Click()

   List1.Clear
   Call GetInstalledCOMPorts(List1)
   
End Sub


Private Sub Command2_Click()

   Dim nPort As Long
   
   List1.Clear
   nPort = GetFirstAvailableCOMPort()
   
   If nPort > 0 Then
      List1.AddItem "COM" & nPort & "  is the first available port"
   End If
   
End Sub


Private Sub Command3_Click()

   Dim Port As Long
   Dim result As Boolean
   
   List1.Clear
   
   Port = GetSelectedOptionIndex() + 1
   
   If COMConfigPort(Port) = 1 Then
      List1.AddItem "COM" & Port & "  - User pressed OK"
   Else
      List1.AddItem "COM" & Port & "  - User pressed Cancel"
   End If

End Sub


Private Sub Command4_Click()

   Call OpenPort(1)
   Command4.Enabled = MSComm2.PortOpen = False

End Sub


Private Sub Command5_Click()

   If MSComm2.PortOpen = True Then
      MSComm2.PortOpen = False
   End If
   
   Command4.Enabled = MSComm2.PortOpen = False
   
End Sub


Private Function COMCheckPort(Port As Long) As Boolean

  'Returns false if port cannot be opened or does not exist
  'Returns true if port is available and can be opened
   
  'Handle all errors
   On Error GoTo OpenCom_Error
   
  'Set port number for test
   MSComm1.CommPort = Port
   
   If MSComm1.PortOpen = True Then
      COMCheckPort = False
      Exit Function
   Else
     'Test the port by opening and closing it
      MSComm1.PortOpen = True
      MSComm1.PortOpen = False
      COMCheckPort = True
      Exit Function
   End If
   
OpenCom_Error:
   COMCheckPort = False
   
End Function


Private Function COMConfigPort(Port As Long) As Boolean

   Dim sPort As String
   
   If Val(Port) > 0 Then
   
      sPort = "COM" & Port & ":"
   
      If Right$(sPort, 1) <> ":" Then
         sPort = sPort & ":"
      End If
            
     'Configure the port on the local machine.
     'This API can also be used to configure
     'COM and LPTP ports on remote machines
     'and servers by passing the machine name
     'as the first parameter in the format
     ' "\\servername". ByVal vbNullString or
     'ByRef 0& can be passed to configure the
     'local machine. The hwnd parameter specified
     'the window that owns the dialog - it will
     'appear modal to the specified window.
     'Returns 1 if OK is pressed, or 0 if Cancelled.
     '
     'This call does not return the values set or
     'changed in the dialog, nor does it indicate
     'whether the user pressed Apply prior to
     'pressing OK or Cancel. This is important
     'in so far as changes made and Applied are
     'set even if the dialog is cancelled.
      COMConfigPort = ConfigurePort(ByVal "\\vbnetdev", Me.hwnd, sPort)
            
   End If

End Function


Private Function GetFirstAvailableCOMPort() As Long

   Dim Port As Long
   
  'Find first port not already in use.
  'Return either the port number if
  'available, or zero otherwise
   For Port = 1 To 16
       
      If COMCheckPort(Port) = True Then
         GetFirstAvailableCOMPort = Port
         Exit Function
      End If
   
   Next Port
   
  'No useable port was found
   GetFirstAvailableCOMPort = 0

End Function


Private Function GetInstalledCOMPorts(lst As ListBox) As Long

   Dim Port As Long
   
  'simply loop through a range of
  'possible ports and pass to the
  'COMCheckPort function
   For Port = 1 To 16
   
      If COMCheckPort(Port) Then
         lst.AddItem "COM" & Port & "  available"
      Else
         lst.AddItem "COM" & Port & "  (not available or no such port)"
      End If
      
   Next

End Function


Private Function GetSelectedOptionIndex() As Long

  'returns the selected item index from
  'a set of option buttons. Use in place
  'of multiple If...Then statements!
  'To add more option buttons to this function
  'just append them to the test condition,
  'setting the multiplier to the next negative
  'value (eg Option3.Value * -2, Option4.Value * -3)
  'Also see GetSelectedOptionIndex in the Core
  'routines for a control array method.
   GetSelectedOptionIndex = Option1.Value * 0 Or _
                            Option2.Value * -1
                            
End Function

Private Function OpenPort(Port As Long) As Boolean

  'Handle all errors
   On Error GoTo OpenPort_Error
   
  'Set port number for test
   MSComm2.CommPort = Port
   
   If MSComm2.PortOpen = True Then
      OpenPort = False
      Exit Function
   Else
     'Test the port by opening and closing it
      MSComm2.PortOpen = True
      
      OpenPort = True
      Exit Function
   End If
   
OpenPort_Error:
   OpenPort = False

End Function
 Comments
 

 
 

PayPal Link
Make payments with PayPal - it's fast, free and secure!

 
 
 
 

Copyright ©1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy

 

Hit Counter