关键在于WaitCommEvent函数
procedure TgSerialPortThread.Execute;
var
dwError: Dword;
tmps:String;
p2:Integer;
lpEvtMask: DWORD;
begin
p2 := 0;
FillChar( OverLap, Sizeof(TOverlapped), 0 );
OverLap.hEvent := CreateEvent( nil, True, False, nil);
while (not Terminated) do
begin
if Assigned(FOnSignal) then Synchronize(DoSignal); //线程内循环的信号感应输出(当串口有事件时,循环明显达到极限速度)
WaitCommEvent(hSerialPort, lpEvtMask, @OverLap); //这个主要是检测串口如果没有活动事件时,让下一句可以等待。
WaitForSingleObject(OverLap.hEvent, 500) ;
tmps := ReadSerialPort();
if tmps.IsEmpty and buftxt.IsEmpty then Continue;
buftxt := buftxt + String(tmps);
p2 := Pos(#13#10, buftxt);
repeat
if p2 > 0 then
begin
//数据业务处理 略