在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