串口通讯编程时 串口如果被占用 怎么才能提示出错?

来源:百度知道 编辑:UC知道 时间:2024/06/27 09:13:53
我的程序 如果出口被占用 程序直接错误无法运行
我想让程序在串口被占用时提示错误 该怎么做?
我用的是delphi mscomm
谢谢
按你说的做了还是不行
需要我把其他代码贴上来吗? 还有我用combobox1改变串口时想要打不开的时候提示 而不是程序直接错误 要怎么做 ?谢谢
procedure TForm1.FormCreate(Sender: TObject);
begin
try
mscomm1.CommPort:=1;
if mscomm1.portopen=false then
mscomm1.Settings:='9600,n,8,1';
mscomm1.portopen:=true;
mscomm1.OutBufferCount:=0;
mscomm1.inBufferCount:=0;
except
begin
showmessage('com1错误!');
application.Terminate;
end;
end;
radiobutton1.checked:=true;
combobox1.Items.add('com1');
combobox1.Items.add('com2');
combobox1.Items.add('com3');
combobox1.Items.add('com4');
combobox1.Items.add('com5');
combobox1.Items.add('com6');
end;

rocedure TForm1.ComboBox1Select(Sender: TObject);
begin
if mscomm1.portopen=true then
mscomm1.portopen:=false;
if

用try ... except结构控制(这种办法最方便也简单,管他是被占用了还是打开失败了)

或者用CreateFile函数来判断,你可以试验下:
var
hNewCommFile:Thandle;
begin
.....
hNewCommFile:=CreateFile(PChar('com1'),GENERIC_READ or GENERIC_WRITE,0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL or FILE_FLAG_OVERLAPPED,0);

if hNewCommFile = INVALID_HANDLE_VALUE then
showmessage('Error opening serial port' );
......
end;

----------------
try
mscomm1.CommPort:=1;
if mscomm1.portopen=false then
mscomm1.Settings:='9600,n,8,1';
mscomm1.portopen:=true;
mscomm1.OutBufferCount:=0;
mscomm1.inBufferCount:=0;
except
begin
showmessage('com1错误!');
application.Terminate;
end;

--------------
。。。。。
except
begin
showmessage('com1错误!');
application.Terminate;
end;
end;//这个end多了,你应该删除掉
。。。。

procedure TForm1.Combo