用API吧,这是一个演示 interface uses Windows,Classes,SysUtils; type TCommThread = class(TThread) private buffer:array[0..2047] of byte;//缓冲区 count:integer;//收到字节数 procedure readPort;//读数据 procedure putData;//输出读到的数据 protected procedure Execute; override; end;implementationprocedure TCommThread.Execute; begin while not Terminated do begin readPort; end; if count > 0 then Synchrocnize(putData); end;procedure TCommThread.readPort; var nBytesRead, dwEvent, dwError:LongWORD; cs:TCOMSTAT; begin if (hComm = 0) then exit;//hComm主线程中定义的全局变量保存串口句柄 ClearCommError(hComm, dwError, @cs); ReadFile(hComm, buffer, cs.cbInQue, nBytesRead, nil); if cs.cbInQue = 0 then exit; if cs.cbInQue > sizeof(buffer) then begin purgeComm(hComm, PURGE_RXCLEAR); exit end; count := cs.cbInQue;end;
interface
uses Windows,Classes,SysUtils;
type
TCommThread = class(TThread)
private
buffer:array[0..2047] of byte;//缓冲区
count:integer;//收到字节数
procedure readPort;//读数据
procedure putData;//输出读到的数据
protected
procedure Execute; override;
end;implementationprocedure TCommThread.Execute;
begin
while not Terminated do
begin
readPort;
end;
if count > 0 then Synchrocnize(putData);
end;procedure TCommThread.readPort;
var
nBytesRead, dwEvent, dwError:LongWORD;
cs:TCOMSTAT;
begin
if (hComm = 0) then exit;//hComm主线程中定义的全局变量保存串口句柄
ClearCommError(hComm, dwError, @cs);
ReadFile(hComm, buffer, cs.cbInQue, nBytesRead, nil);
if cs.cbInQue = 0 then exit;
if cs.cbInQue > sizeof(buffer) then
begin
purgeComm(hComm, PURGE_RXCLEAR);
exit
end;
count := cs.cbInQue;end;