看看是否可行?<br>unit Unit1;<br><br>interface<br><br>uses<br> Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,<br> Dialogs, StdCtrls;<br><br>const<br> WM_CommNotify=WM_User+100; <br><br>type<br> TForm1 = class(TForm)<br> procedure FormCreate(Sender: TObject);<br> private<br> { Private declarations }<br> procedure Comminitialize;<br> procedure MsgCommProcess(var Message:Tmessage); Message Wm_CommNotify;<br> public<br> { Public declarations }<br> end;<br> TComm=Class(TThread)<br> protected<br> procedure Execute;override;<br> end;<br><br>var<br> Form1: TForm1;<br><br>implementation<br><br>{$R *.dfm}<br>var<br> hCom,Post_Event:THandle;<br> lpOL
Overlapped;<br><br>procedure TForm1.Comminitialize; //串行口初始化;<br>var<br> lpDCB:TDcb;<br>begin<br> hCom:=CreateFile('COM2',Generic_Read or Generic_Write,0,nil,Open_Existing,<br> File_Attribute_Normal or File_Flag_Overlapped,0); //打开串行口;<br> if hCom=Invalid_handle_Value then<br> else begin<br> setupcomm(hcom,4096,4096); //设置输入,输出缓冲区皆为4096字节;<br> getcommstate(hcom,lpdcb); //获取串行口当前默认设置;<br> lpDCB.baudrate:=2400;<br> lpDCB.StopBits:=1;<br> lpDCB.ByteSize:=8;<br> lpDCB.Parity:=EvenParity; //偶校验;<br> SetCommState(hcom,lpdcb);<br> SetCommMask(hcom,ev_rxchar);//指定串行口事件为接收到字符;<br> end;<br>end;<br><br>procedure TForm1.FormCreate(Sender: TObject);<br>begin<br> Comminitialize;<br> Post_Event:=CreateEvent(nil,true,true,nil); //创建同步事件;<br> TComm.Create(False); //创建串行口监视线程;<br>end;<br>{ TComm }<br><br>procedure TComm.Execute;<br>var<br> dwEvtMask
word;<br> Wait:Boolean;<br>begin<br> FillChar(lpOL,SizeOf(TOverlapped),0);<br> while True do<br> begin<br> dwEvtMask:=0;<br> Wait:=WaitCommEvent(hcom,dwevtmask,lpol); //等待串行口事件;<br> if Wait then<br> begin<br> WaitForSingleObject(Post_Event,INFINITE); //等待同步事件置位;<br> ResetEvent(Post_Event); //同步事件复位;<br> PostMessage(Form1.Handle,WM_COMMNOTIFY,0,0); //发送消息;<br> end;<br> end;<br>end;<br><br>procedure TForm1.MsgCommProcess(var Message:Tmessage);<br>begin<br> ShowMessage('......'); //设备打开或关闭;<br>end;<br><br>end.