在Win95系统中,串行口和串行通信驱动程序是通过一个数据结构进行配置的,这个数据结构被称为设备控制块( Device Control Block ),简称DCB。Win95的DCB比Windows 3.x的DCB更复杂,对数据结构的定义更完善。
下面是Win95中设备控制块数据结构的定义:
Type DCB ’在Win95 API中有详细定义,可从VB4的API Text Viewer中得到 DCBlength As Long BaudRate As Long fBinary As Long fParity As Long …… EvtChar As Byte End Type Win95为获取通讯端口的状态提供了重要的GetCommState函数。函数把端口的配置信息装入一个设备控制块DCB,从而获得端口的配置情况。
另一个重要的COMSTAT结构则通常被用来描述串口当前的状态。其定义如下:
Type COMSTAT ’在Win95 API中有详细定义,可从VB4的API Text Viewer中得到 fCtsHold As Long fDsrHold As Long …… cbInQue As Long cbOutQue As Long End Type 通常可按以下四步实现串行通信:
以下是甲方(PC机)的几个子函数的程序实例。 Private Function OpenThePort(cPort as String,cBaud as String,cParity as String,cData as String,tStops as String)As Boolean Dim lResult as Long Dim lHandle as Long Dim DCB_COMM as DCB Dim cDCBConfig as String lHandle = CreateFile(cPort,GENERIC_READ Or GENERIC_WRITE,0&,0&,OPEN_EXISTING,0&,0&) If lHandle = -1 Then ’打开串口失败 OpenThePort = False MsgBox “串口可能正被其他应用程序占用!” lResult = CloseHandle(lHandle) ’先关闭串口后再打开 If lResult = 0 Then OpenThePort Exit Function End If End If cDCBConfig.band = 2400 ’设置DCB cDCBConfig.parity = None cDCBConfig.data = 8 cDCBConfig.stop = 1 lResult = BuildCommDCB(cDCBConfig,DCB_COMM) ’按用户设定配置一个DCB结构 If lResult = 0 Then OpenThePort = False MsgBox “无法建立DCB设备控制块” Exit Function End If lResult = SetCommState(lHandle,DCB_Comm) ’实际设置一个串口的DCB If lResult = 0 Then OpenThePort = False MsgBox “无法建立DCB设备控制块” Exit Function End If OpenThePort = True End Function
Private Sub SendHand ( ) ’发送握手信号的子过程 Dim Nchars As Long Static Readbuff As String * 1 Static Writebuff As String * 1 Dim lpDCB As DCB Dim lRet As Long Dim lHandle As Long Dim lpOverlapped As OVERLAPPED Dim RNum As Integer
MsgBox “请把电卡读卡器插在串口2上!”,48,“提示窗口” lHandle = OpenThePort(COMM1,2400,None,8,1) lRet = PurgeComm( lHandle,1 ) ’清输出缓冲区 lRet = PurgeComm( lHandle,0 ) ’清输入缓冲区 lRet = GetCommState ( lHandle,lpDCB ) ’获得通讯口的状态 Shand: Writebuff$ = Chr$(&H8F) lRet = WriteFile ( lHandle,Writebuff$,1,Nchars,lpOverlapped ) ’送握手信号入串口缓冲区 If lRet <= 0 Then MsgBox “发送操作出错,电卡握手信号未发送成功”, 16 GoTo Shand ’不成功则重发 Else GoTo Qtest End If GoTo Shand Qtest: Readbuff$ =“ ” ’清除缓冲区为空 Do While lHandle ’循环查询串口 RNum = 0 ’设置读串口次数的指针为0 ReadAgain: lRet = ReadFile( lHandle,Readbuff$,1,Nchars,lpOverlapped ) If lRet < 0 Then MsgBox “读取应答信号时出错”, 16 End If If lRet = 0 Then If RNum > 1000 Then ’只读1000次串口,以免陷入死循环 MsgBox "电卡没有插接好或电卡没有接在串口上!" GoTo CloseP End If RNum = RNum + 1 GoTo ReadAgain End If If Hex$(Asc(Readbuff)) <> Hex$(&HFF) Then GoTo Shand ’回送码不正确则返回继续发送握手信号 Else Label1.Caption = “握手信号是:”+Hex$(Asc(Readbuff$)) Msgbox “握手信号正确,已正确联机” GoTo CloseP End If Loop CloseP: lRet = CloseHandle( lHandle ) If lRet = 0 Then MsgBox “串行通讯口关闭成功”,48,“提示窗口” End If End Sub