1。如你怕打开端口出错,可用try..except ..end 结构处理异常,如果出错你可提示本端口不可用,提示用户选择其他端口。 2。如你想测试那个端口是否可用,你可以用mscomm或spcomm控件测试一下,如果串口被占用或不存在就会触发异常,你再根据返回错误提示判断那个端口是被占用还是不存在,如mscomm控件,错误码8002是端口不存在,8005是端口已被占用。 下面是用spcomm控件,测试端口的代码, for j:=1 to 10 do //找系统端口 begin comm1.CommName:='com'+inttostr(j); try comm1.StartComm; //标记本端口可用 memo1.Lines.Add('串口'+inttostr(j)+'可用'); comm1.StopComm; except //标记本端口不可用 memo1.Lines.Add('串口'+inttostr(j)+'不可用'); end; end; nextStartcomm方法用于打开串口,当打开失败时通常会报错。错误主要有 7种:⑴串口已经打开;⑵打开串口错误;⑶文件句柄不是通信句柄;⑷不能够安装通信缓存;⑸不能产生事件;⑹不能产生读进程;⑺不能产生写进程; 返回包括: 'This serial port already opened' 'Error opening serial port' 'File handle is not a comm handle' 'Cannot setup comm buffer' 'Unable to create event' 'Unable to create read thread' 'Unable to create write thread'
2。如你想测试那个端口是否可用,你可以用mscomm或spcomm控件测试一下,如果串口被占用或不存在就会触发异常,你再根据返回错误提示判断那个端口是被占用还是不存在,如mscomm控件,错误码8002是端口不存在,8005是端口已被占用。
下面是用spcomm控件,测试端口的代码,
for j:=1 to 10 do //找系统端口
begin
comm1.CommName:='com'+inttostr(j);
try
comm1.StartComm;
//标记本端口可用
memo1.Lines.Add('串口'+inttostr(j)+'可用');
comm1.StopComm;
except
//标记本端口不可用
memo1.Lines.Add('串口'+inttostr(j)+'不可用');
end;
end;
nextStartcomm方法用于打开串口,当打开失败时通常会报错。错误主要有 7种:⑴串口已经打开;⑵打开串口错误;⑶文件句柄不是通信句柄;⑷不能够安装通信缓存;⑸不能产生事件;⑹不能产生读进程;⑺不能产生写进程;
返回包括:
'This serial port already opened'
'Error opening serial port'
'File handle is not a comm handle'
'Cannot setup comm buffer'
'Unable to create event'
'Unable to create read thread'
'Unable to create write thread'