新项目中要求监测串口。因本人从未写过串口和多线程的程序。所以请教大家们!本程序为PDA设备通过pc网络服务器下载数据,pc上运行下载程序。本程序运行后要采用线程监测串口。因此串口通信可能采用 API  函数或者是MSComm 组件。所以MSComm能否被线程使用?请教各位前辈提供些经验或者是实例代码

解决方案 »

  1.   

    用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;