用DELPHI编写

源代码在线查看: com.pas

软件大小: 6 K
上传用户: a215290209
关键词: DELPHI 编写
下载地址: 免注册下载 普通下载 VIP

相关代码

				unit com;
				
				interface
				
				uses
				  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
				  Dialogs;
				
				  const
				     Wm_commNotify=Wm_User+12;
				type
				  TForm1 = class(TForm)
				    procedure FormCreate(Sender: TObject);
				  private
				  procedure comminitialize;
				  procedure MsgcommProcess(Var Message:Tmessage);
				  Message Wm_commnotify;
				    { Private declarations }
				  public
				    { Public declarations }
				  end;
				  //线程声明
				  Tcomm=class(TThread)
				  protected
				   procedure Execute;override;
				   end;
				
				var
				  Form1: TForm1;
				  hcom,Post_Event:Thandle;
				  lpol:Poverlapped;
				
				implementation
				
				{$R *.dfm}
				
				
				procedure Tcomm.Execute;//线程招待过程
				var
				dwEvtMask:Dword;
				Wait:Boolean;
				begin
				fillchar(lpol,sizeof(toverlapped),0);
				while true do begin
				    dwEvtMask:=0;
				    Wait:=WaitCommEvent(hcom,dwevtmask,lpol); //等待串行口事件
				if wait then begin
				  waitforsingleobject(post_event,infinite);//等待同步事件置位
				  resetevent(post_event);//同步事件复位
				  postmessage(Form1.Handle,WM_COMMNOTIFY,0,0);//发送消息
				  end;
				 end;
				end;
				
				procedure Tform1.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
				   else
				     setupcomm(hcom,4096,4096);//设置输入。输出缓冲区为4096字节
				     getcommstate(hcom,lpdcb);//获取串口当前默认设置
				     lpdcb.BaudRate :=2400;
				     lpdcb.StopBits :=1;
				     lpdcb.ByteSize :=8;
				     lpdcb.Parity :=EvenParity;//偶校验
				     setcommstate(hcom,lpdcb);
				     setcommMask(hcom,ev_rxchar);//指定串口事件为接收到字符
				end;
				
				
				procedure Tform1.Msgcomm ;
				process(var Message:Tmessage);
				var
				clear:boolean;
				coms:Tcomstat;
				cbNum,ReadNumber,lpErrors:integer;
				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);//处理接收数据
				   setEvent(post_Event);//同步事件置位
				   end;
				 end;  
				
				procedure TForm1.FormCreate(Sender: TObject);
				begin
				comminitialize;
				post_event:=createEvent(nil,true,true,nil);//创建同步事件
				Tcomm.create(false);//创建串行口监视线程
				
				
				end;
				
				end.
							

相关资源