基本信息
源码名称:delphi 串行通信 示例源码(连接串口、断开串口)
源码大小:0.17M
文件格式:.zip
开发语言:Pascal
更新时间:2019-10-01
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300

本次赞助数额为: 2 元 
   源码介绍


unit PMain;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;
const
  WM_COMMNOTIFY=WM_USER 12;

type
  TMainForm = class(TForm)
    ComboBox1: TComboBox;
    Button1: TButton;
    Label1: TLabel;
    Button2: TButton;
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    Procedure CommInitialize;
    Procedure MsgCommProcess(var Message:TMessage);Message WM_COMMNOTIFY;
  public
    { Public declarations }
  end;
  TComm= class(TThread)
  protected
    Procedure Execute;override;
  end;

var
  MainForm: TMainForm;
  hcom,Post_Event:Thandle;
  lpol:Poverlapped;

implementation

{$R *.DFM}

{ TComm }

procedure TComm.Execute;
var
  dwEvtMask:Dword;
  Wait:Boolean;
begin
  fillchar(lpol,sizeof(lpol),0);
  While True do
    begin
      dwEvtMask:=0;
      Wait:=WaitCommEvent(hcom,dwEvtMask,lpol);
      if Wait then
        begin
          WaitForSingleObject(Post_Event,infinite);
          PostMessage(MainForm.Handle,WM_COMMNOTIFY,0,0);
        end;
    end;
  inherited;

end;

{ TMainForm }

procedure TMainForm.CommInitialize;
var
  lpdcb:Tdcb;
begin
  hcom:=CreateFile('Com2',generic_read or generic_write,0,nil,open_existing,file_attribute_normal or file_flag_overlapped,0);
  if hcom=invalid_handle_value then
    begin
      ShowMessage('端口初始化成功');
    end
  else
    begin
      SetUpComm(hcom,4096,4096);
    end;

  GetCommState(hcom,lpdcb);
  lpdcb.BaudRate:=2400;
  lpdcb.StopBits:=1;
  lpdcb.ByteSize:=8;
  lpdcb.Parity:=EvenParity;
  SetCommState(hcom,lpdcb);
  SetCommMask(hcom,ev_rxchar);

end;

procedure TMainForm.MsgCommProcess(var Message: TMessage);
var
  Clear:Boolean;
  Coms:TComstat;
  cbNum,ReadNumber,lpErrors:cardinal;
  Read_Buffer:array[1..100] of char;
begin
  Clear:=ClearCommError(hcom,lpErrors,@Coms);
  if Clear then
    begin
      cbNum:=Coms.cbInQue;
      ReadFile(hcom,Read_Buffer,cbNum,ReadNumber,lpol);
      ShowMessage(Read_Buffer);
      SetEvent(Post_Event);
    end;

end;

procedure TMainForm.FormCreate(Sender: TObject);
begin
  CommInitialize;
  Post_Event:=CreateEvent(nil,true,true,nil);
  TComm.Create(False);
end;

end.