home *** CD-ROM | disk | FTP | other *** search
/ Visual Basic Source Code / Visual Basic Source Code.iso / vbsource / comm / simpcomm.frm (.txt) < prev    next >
Encoding:
Visual Basic Form  |  1995-05-08  |  17.3 KB  |  403 lines

  1. VERSION 2.00
  2. Begin Form Form1 
  3.    BackColor       =   &H00C0C0C0&
  4.    BorderStyle     =   1  'Fixed Single
  5.    Caption         =   "Form1"
  6.    ClientHeight    =   4230
  7.    ClientLeft      =   1080
  8.    ClientTop       =   1815
  9.    ClientWidth     =   7365
  10.    Height          =   4635
  11.    Icon            =   SIMPCOMM.FRX:0000
  12.    Left            =   1020
  13.    LinkMode        =   1  'Source
  14.    LinkTopic       =   "Form1"
  15.    MaxButton       =   0   'False
  16.    MinButton       =   0   'False
  17.    ScaleHeight     =   4230
  18.    ScaleWidth      =   7365
  19.    Top             =   1470
  20.    Width           =   7485
  21.    WindowState     =   1  'Minimized
  22.    Begin CommandButton Command_Send 
  23.       Caption         =   "Send Text"
  24.       Height          =   1215
  25.       Left            =   1080
  26.       TabIndex        =   0
  27.       Top             =   2160
  28.       Width           =   1695
  29.    End
  30.    Begin Timer Timer_ClearStatusMessage 
  31.       Left            =   120
  32.       Top             =   600
  33.    End
  34.    Begin TextBox Text_Display 
  35.       BackColor       =   &H00C0C0C0&
  36.       FontBold        =   -1  'True
  37.       FontItalic      =   0   'False
  38.       FontName        =   "Courier"
  39.       FontSize        =   9.75
  40.       FontStrikethru  =   0   'False
  41.       FontUnderline   =   0   'False
  42.       Height          =   1580
  43.       Left            =   1080
  44.       MultiLine       =   -1  'True
  45.       TabIndex        =   1
  46.       Top             =   160
  47.       Width           =   5175
  48.    End
  49.    Begin Timer Timer_CheckReceiveBuffer 
  50.       Left            =   120
  51.       Top             =   120
  52.    End
  53.    Begin Label Label_StatusBar 
  54.       BackColor       =   &H00C0C0C0&
  55.       ForeColor       =   &H00000000&
  56.       Height          =   620
  57.       Left            =   360
  58.       TabIndex        =   2
  59.       Top             =   3520
  60.       Width           =   6375
  61.    End
  62. '*************************************************
  63. '* GENERAL DECLARATIONS section of Form1
  64. '*************************************************
  65. DefInt A-Z
  66. Dim DCB As CommStateDCB     'COM Device Control Block (DCB) record structure variable
  67.                 'This is a parameter needed by the Windows SetCommState API
  68.                 'function.
  69.                 'Refer to Form_Load event procedure for an example of
  70.                 'how initialize the COM DCB
  71. Dim CommStat As COMSTAT     'COM status variable.
  72.                 'This is a parameter needed by the Windows GetCommError API
  73.                 'function
  74. Dim ComID                   'Identifies the COM port that was opened.
  75.                 'Used by or returned by the Windows API functions
  76.                 'OpenComm, GetCommState, SetCommEventMask, GetCommEventMask,
  77.                 'ReadComm, WriteComm, FlushComm, CloseComm
  78. '**************************************************************
  79. '* This event procedure demonstrates how to call the Windows
  80. '* API function WriteComm to send data out the COM port.
  81. '* Click event procedure for the command button
  82. '* (CtlName: Command_Send) that causes the contents
  83. '* of the text box (CtlName: Text_Display) to be sent
  84. '* out the COM port.
  85. '* Status information is displayed within caption of a
  86. '* label (CtlName: Label_StatusBar).
  87. '***************************************************************
  88. Sub Command_Send_Click ()
  89.     'Get the data to be sent from the text box.  Note: All
  90.     'of the text contained in the text box is sent.
  91.     buffer$ = Text_Display.text
  92.     'Send the contents of the output buffer out the COM port
  93.     r = WriteComm(ComID, buffer$, Len(buffer$))
  94.     'Display any communications errors that might have occurred
  95.     'when attempting to write to the COM port
  96.     Call ProcessCommError
  97. End Sub
  98. '****************************************************************************
  99. '* Form_Load event procedure for Form1
  100. '* This is starting point of the program.
  101. '* Create the following controls with the
  102. '* following CtlNames on Form1:
  103. '* Control
  104. '* (Default Name)     CtlName                  Notes
  105. '* --------------     -------                  ---------------------------------
  106. '*   Text1            Text_Display             Set the MultiLine property to True
  107. '*   Command1         Command_Send             Set caption property to "Send Text"
  108. '*   Timer1           Timer_CheckReceiveBuffer
  109. '*   Timer2           Timer_ClearStatusMessage
  110. '*   Label1           Label_StatusBar
  111. '* This event procedure demonstrates how to call the Windows API functions,
  112. '* OpenComm and SetCommState to open the COM port.  In this example, the
  113. '* COM port is opened as the following equivalent QuickBASIC OPEN COM string:
  114. '*     "COM1:1200,N,8,1,DS0,CS0,CD0,RS,TB2048,RB2048"
  115. '******************************************************************************
  116. Sub Form_Load ()
  117.     'Move the COM status window to the bottom of the form
  118.     Label_StatusBar.Move 0, Label_StatusBar.Top, Form1.ScaleWidth
  119.     Form1.Show
  120.     'Show a status message indicating that the COM port is being opened
  121.     Call ShowStatus("Opening COM1 ...")
  122.     Do
  123.     'Open COM1 with a 2K input and output buffer
  124.     ComID = OpenComm("COM2", 2048, 2048)
  125.     If ComID < 0 Then
  126.         Call ShowOpenCommError(ComID)
  127.         If ComID = IE_OPEN Then
  128.         m$ = "COM device already opened" + Chr$(13) + Chr$(13)
  129.         m$ = m$ + "Do you wish to use it anyway"
  130.         Response = MsgBox(m$, 36, "Communications Error")
  131.         'Close the com port if the user selected Yes from the message box
  132.         If Response = 6 Then
  133.             'Close the COM port if the user decided to use it anyway
  134.             r = CloseComm(Asc(DCB.Id))
  135.         Else
  136.             
  137.             'Display a message and terminate the program
  138.             'if the user decided not to use the COM port
  139.             'that is currently open
  140.             m$ = "Terminating application"
  141.             MsgBox m$, 16, "Communications Abort"
  142.             End
  143.         End If
  144.         Else
  145.         'Display a critical error message and terminate the program
  146.         m$ = "Error occurred attempting to open the COM port."
  147.         m$ = m$ + "  Check connection, settings and rerun the program"
  148.         MsgBox m$, 16, "Communications Error"
  149.         End
  150.         End If
  151.     Else
  152.         'Set line settings for the COM port as 1200:N,8,1,CD0,CS0,DS0,RS,TB2048,RB2048
  153.         '
  154.         'The following parameter settings represent the default settings set by calling
  155.         'BuildCommDCB in the Form_Load event procedure.
  156.         '
  157.         'Set parameters as 1200: N,8,1
  158.         DCB.Id = Chr$(ComID)
  159.         DCB.BaudRate = 1200             'Other possible values include 300, 2400, 4800, 9600, 19200
  160.         DCB.ByteSize = Chr$(8)          'Other possible values include 4,5,6,7
  161.         DCB.Parity = Chr$(NOPARITY)     'Other possible values include EVENPARITY, MARKPARITY, ODDPARITY, SPACEPARITY
  162.         DCB.StopBits = Chr$(ONESTOPBIT) 'Other possible values include ONE5STOPBITS, TWOSTOPBITS
  163.                     
  164.         'Set timeout period for CD, CS and DS handshake lines respectively.  Values
  165.         'represent milliseconds.  A value of zero represents an infinite wait effectively
  166.         'disabling handshaking on that line.  Possible values can range from 0 to 65,535
  167.         'for an unsiged integer or -32,768 to 32,767 for signed integers.
  168.         '
  169.         DCB.RlsTimeOut = 0         'Carrier detect or receive-line-signal-detect (CD or RLSD) line (CD0)
  170.         DCB.CtsTimeOut = 0         'Clear-to-send (CTS) line (CS0)
  171.         DCB.DsrTimeOut = 0         'Data-set-ready (DSR) line (DS0)
  172.         
  173.         'The following bit flags are combined in the ModeControl field below.  Because
  174.         'the following are bit fields they cannot be represented as a field of a Type ... End Type
  175.         'structure
  176.         
  177.         'DCB.fBinary = 1            Specify binary mode.  Setting this to zero causes an
  178.         '                           EOF character (Chr$(26)) to signal the end of data.
  179.         'DCB.fRtsDisabled = 1       Disable request-to-send line (RS).  A zero value enables
  180.         '                           the request-to-send line
  181.         'DCB.fParity = 0            Disable parity checking.  A value of 1 enables parity checking
  182.         'DCB.fOutCtsFlow = 0        Disable checking of clear-to-send line for output flow control
  183.         'DCB.fOutxDsrFlow = 0       Disable checking of data-set-ready (DSR) line for output flow control
  184.         'DCB.fDummy = 0 + 0         Two bit reserved field
  185.         'DCB.fDtrDisabled = 1       Disable the data-set-ready line (DTR).  A value of 1 enables DTR.
  186.         '
  187.         'DCB.fOutX = 0              Disable XON/XOFF during transmission.
  188.         '                           A value of 1 enables XON/XOFF.
  189.         'DCB.fInX = 0               Disable XON/XOFF during reception.
  190.         '                           A value of 1 enables XON/XOFF
  191.         'DCB.fPeChar = 0            Disable the replace of parity error characters with the character
  192.         '                           contained in the PeChar field.  A value of 1 enables replacement
  193.         '                           of parity error characters with the character contained in the
  194.         '                           PeChar field.
  195.         '
  196.         'DCB.fNull = 0              Received null characters are not to be discarded.  A value of 1
  197.         '                           specifies that null characters received will be discarded.
  198.         '
  199.         'DCB.fChEvt = 0             Reception of the character contained in the EvtChar field does
  200.         '                           not signify an event.  A value of 1 indicates that the
  201.         '                           reception of a character identical to the character contained
  202.         '                           in the EvtChar field signifies and event.
  203.         '
  204.         'DCB.fDtrFlow = 0           The DTR line is not used for receive flow control.  A value of 1
  205.         '                           indicates that the DTR line is used for receive flow control.
  206.         'DCB.fRtsFlow = 0           The RTS line is not used for receive flow control.  A value of 1
  207.         '                           indicates that the DTR line is used for receive flow control.
  208.         'DCB.fDummy = 0             Reserved
  209.         '
  210.         '1100 0001 0000 0000        Binary representation
  211.         '                           of the above bit settings
  212.         '
  213.         '  C    1    0    0         Hex representation of the above
  214.         '                           bit settings
  215.         DCB.ModeControl = &H83     'Based on the bit settings above
  216.         DCB.XonChar = Chr$(0)
  217.         DCB.XoffChar = Chr$(0)
  218.         DCB.XonLim = 0
  219.         DCB.XoffLim = 0
  220.         DCB.peChar = Chr$(0)
  221.         DCB.EofChar = Chr$(26)
  222.         DCB.EvtChar = Chr$(0)
  223.         Call ShowStatus("Setting COM State ... ")
  224.         'Set the COM port with the settings as indicated above
  225.         r = SetCommState(DCB)
  226.         
  227.         If r < 0 Then
  228.         m$ = "Error occurred during initialization of COM settings."
  229.         m$ = m$ + "  Check connection, settings and rerun this program"
  230.         MsgBox m$, 16, "Communications Error"
  231.         Unload Form1
  232.         Else
  233.         'Start the timer to continuously check the receive buffer
  234.         'Start the timer only if no errors occurred
  235.         Timer_CheckReceiveBuffer.Interval = 1
  236.         Timer_CheckReceiveBuffer.Enabled = True
  237.         'Set the focus on the text box
  238.         Text_Display.SetFocus
  239.         End If
  240.     End If
  241.     Loop While ComID < 0
  242. End Sub
  243. '***************************************************************************
  244. '* This event procedure demonstrates how to call the Windows API functions
  245. '* FlushComm and CloseComm to close the COM port.
  246. '* Close the COM port and end the program.
  247. '***************************************************************************
  248. Sub Form_Unload (Cancel As Integer)
  249.     'Flush the COM transmit and receive buffers.  Note: the return value represents
  250.     'the success of the FlushComm function call.  Zero = success; Negative = non-success
  251.     'The return value is ignored in this example.
  252.     r = FlushComm(ComID, 0)   'Flush all characters in the transmit buffer
  253.     r = FlushComm(ComID, 1)   'Flush all characters in the receive buffer
  254.     r = CloseComm(ComID)
  255.     If r < 0 Then
  256.     MsgBox "Error Closing the COM Port", 48, "Communications Error"
  257.     End If
  258.     End
  259. End Sub
  260. '**********************************************************************
  261. '* Display message boxes for any communications
  262. '* errors that may occurred when attempting to read from or write to
  263. '* the COM port.  Since more than 1 error can occur when attempting
  264. '* to read from or write to the COM port, several messages boxes may
  265. '* be displayed.
  266. '* IMPORTANT: If an error occurs during communications, Windows locks
  267. '*            the COM port.  The COM port can only be unlocked by
  268. '*            calling the Windows API function GetCommError.
  269. '**********************************************************************
  270. Sub ProcessCommError ()
  271.     CR$ = Chr$(13)      'Character representing a carriage-return
  272.     'Find out if an error occurs.  Calling GetCommError clears
  273.     'the error and causes Windows to unlock the COM port.
  274.     e = GetCommError(ComID, CommStat)
  275.     If e <> 0 Then
  276.     If (e And CE_BREAK) = CE_BREAK Then
  277.         message$ = "Break condition detected"
  278.         GoSub ShowMessage
  279.     End If
  280.     If (e And CE_CTSTO) = CE_CTSTO Then
  281.         message$ = "Clear-to-send (CTS) timeout"
  282.         GoSub ShowMessage
  283.     End If
  284.     If (e And CE_DSRTO) = CE_DSRTO Then
  285.         message$ = "Data-set-ready (DSR) timeout"
  286.         GoSub ShowMessage
  287.     End If
  288.     If (e And CE_DNS) = CE_DNS Then
  289.         message$ = "Parallel device is not selected"
  290.         GoSub ShowMessage
  291.     End If
  292.     If (e And CE_FRAME) = CE_FRAME Then
  293.         message$ = "Framing error detected"
  294.         GoSub ShowMessage
  295.     End If
  296.     If (e And CE_IOE) = CE_IOE Then
  297.         message$ = "Device I/O error occurred" + CR$
  298.         message$ = message$ + "attempting to communicate with parallel device"
  299.         GoSub ShowMessage
  300.     End If
  301.     If (e And CE_MODE) = CE_MODE Then
  302.         message$ = "Requested mode is not supported"
  303.         GoSub ShowMessage
  304.     End If
  305.     If (e And CE_OOP) = CE_OOP Then
  306.         message$ = "Out of paper on parallel device"
  307.         GoSub ShowMessage
  308.     End If
  309.     If (e And CE_OVERRUN) = CE_OVERRUN Then
  310.         message$ = "Overrun error detected"
  311.         GoSub ShowMessage
  312.     End If
  313.     If (e And CE_PTO) = CE_PTO Then
  314.         message$ = "Timeout attempting to communicate with" + CR$
  315.         message$ = message$ + "parallel device"
  316.         GoSub ShowMessage
  317.     End If
  318.     If (e And CE_RLSDTO) = CE_RLSDTO Then
  319.         message$ = "Receive-line-signal-detect timeout"
  320.         GoSub ShowMessage
  321.     End If
  322.     If (e And CE_RXOVER) = CE_RXOVER Then
  323.         message$ = "Receive buffer overflow"
  324.         GoSub ShowMessage
  325.     End If
  326.     If (e And CE_RXPARITY) = CE_RXPARITY Then
  327.         message$ = "Parity error detected"
  328.         GoSub ShowMessage
  329.     End If
  330.     If (e And CE_TXFULL) = CE_TXFULL Then
  331.         message$ = "Transmit buffer full"
  332.         GoSub ShowMessage
  333.     End If
  334.     End If
  335. Exit Sub
  336. ShowMessage:
  337.     MsgBox message$, 48, "Communications Error"
  338.     Return
  339. End Sub
  340. '****************************************************************
  341. '* Displays a message box for any communications error that
  342. '* may have occurred while attempting to open the COM port.
  343. '****************************************************************
  344. Sub ShowOpenCommError (ErrorCode)
  345.     Select Case ErrorCode
  346.     Case IE_BADID
  347.         message$ = "Invalid or unsupported ID"
  348.     Case IE_BAUDRATE
  349.         message$ = "Unsupported baud rate"
  350.     Case IE_BYTESIZE
  351.         message$ = "Invalid byte size"
  352.     Case IE_DEFAULT
  353.         message$ = "Error in default parameters"
  354.     Case IE_HARDWARE
  355.         message$ = "Hardware not present"
  356.     Case IE_MEMORY
  357.         message$ = "Unable to allocate queues"
  358.     Case IE_NOPEN
  359.         message$ = "Device not open"
  360.     Case IE_OPEN
  361.         message$ = "Device already opened"
  362.     End Select
  363.     MsgBox message$, 48, "Communications Error"
  364. End Sub
  365. '**********************************************************
  366. '* Show a COM status message at the bottom of the form
  367. '**********************************************************
  368. Sub ShowStatus (StatusMsg$)
  369.     'Show the message
  370.     Label_StatusBar.Caption = StatusMsg$
  371.     Label_StatusBar.Refresh
  372.     'Set the timer interval to clear the message
  373.     Timer_ClearStatusMessage.Interval = 3000
  374.     Timer_ClearStatusMessage.Enabled = True
  375. End Sub
  376. '************************************************************
  377. '* This event procedure demonstrates how to call the Windows
  378. '* API function ReadComm to read information from the COM
  379. '* port
  380. '************************************************************
  381. Sub Timer_CheckReceiveBuffer_Timer ()
  382.     'Read in up to 2K of data from the COM receive buffer
  383.     buffer$ = Space$(2048)
  384.     'Read characters waiting in the receive buffer.
  385.     r = ReadComm(ComID, buffer$, Len(buffer$))
  386.     'If characters were returned in the buffer, display them
  387.     'in the text box.  The absolute value of the return value
  388.     'for ReadComm indicates how many characters were read from the COM.
  389.     If r <> 0 Then
  390.     Text_Display.SelStart = Len(Text_Display.text)
  391.     Text_Display.SelText = Left$(buffer$, Abs(r))
  392.     End If
  393.     'Display any errors that may have occurred reading from the COM
  394.     Call ProcessCommError
  395. End Sub
  396. '**********************************************************
  397. '* Clear the COM status window and disable the timer
  398. '**********************************************************
  399. Sub Timer_ClearStatusMessage_Timer ()
  400.     Label_StatusBar.Caption = ""
  401.     Timer_ClearStatusMessage.Enabled = False
  402. End Sub
  403.