这个程序是没有控件的直接用API
源码如下
procedure TForm1.btnSendClick(Sender: TObject);
var
Temp:string;
lrc:LongWord;
begin
if (hComm=0) then exit;
Temp:=msend.Text ;
WriteFile(hComm,Pointer(Temp)^,Length(Temp), lrc, nil); //送出数据
end;
procedure TForm1.btnOpenPortClick(Sender: TObject);
begin
//若通信端口已打开,则不需要再打开
if (hComm<>0) then begin
ShowMessage('通信端口已打开!不需再开!');
exit;
end;
OpenComm;
end;
//以下是打开通信端口的程序
procedure TForm1.OpenComm;
var
cc:TCOMMCONFIG;
Temp:string;
begin
Temp:='COM'+inttostr(rdcom.ItemIndex+1); //选择所要打开的COM
hComm:=CreateFile(PChar(Temp), GENERIC_READ or GENERIC_WRITE,
0, nil, OPEN_EXISTING, 0, 0); //打开COM
if (hComm = INVALID_HANDLE_VALUE) then begin //如果COM 未打开
MessageBox (0, '打开通信端口错误!!','',MB_OK);
exit;
end;
GetCommState(hComm,cc.dcb); // 得知目前COM 的状态
cc.dcb.BaudRate:=CBR_9600; // 设置波特率为9600
cc.dcb.ByteSize:=8; // 字节为 8 bit
cc.dcb.Parity:=NOPARITY; // Parity 为 None
cc.dcb.StopBits:=ONESTOPBIT; // 1 个Stop bit
if not SetCommState(hComm, cc.dcb) then begin // 设置COM 的状态
MessageBox (0, '通信端口设置错误!!!','',MB_OK);
CloseHandle(hComm);
exit;
end;
end;
procedure TForm1.btnEndClick(Sender: TObject);
begin
CloseHandle(hComm);//关闭通信端口
close;//结束程序
end;
//定时器事件
procedure TForm1.Timer1Timer(Sender: TObject);
var
Temp : string;
inbuff: array[0..2047] of Char;
nBytesRead, dwError:LongWORD ;
cs:TCOMSTAT;
begin
ClearCommError(hComm,dwError,@CS); //取得状态
if cs.cbInQue =0 then exit;
if cs.cbInQue > sizeof(inbuff) then begin
PurgeComm(hComm, PURGE_RXCLEAR); // 清除COM 数据?
exit;
end;
ReadFile(hComm, inbuff,cs.cbInQue,nBytesRead,nil); // 接收COM 的数据
Temp:=Copy(inbuff,1,cs.cbInQue);
mReceive.Text :=mReceive.Text + Temp; // 将数据显示于Memo1 上 ?
mReceive.SetFocus ;
mReceive.SelStart :=Length(mReceive.Text);
mReceive.SelLength :=0;//将Memo的显示位置移到最下端
end;
//以下是处理按键动作
procedure TForm1.mSendKeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then btnSendClick(Sender);
end;
end.