共同讨论:API串口通信问题!
部分代码如下:
unit communate;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,ShellAPI, OleCtrls, MSCommLib_TLB;
const
Wm_CommNotify=Wm_user+2;
type
TForm1 = class(TForm)
Button1: TButton;
MSComm1: TMSComm;
procedure FormCreate(Sender: TObject);
procedure Button1Click(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
Form1: TForm1;
hcom,Post_Event:Thandle;
lpol:TOverLapped;
implementation
{$R *.dfm}
Procedure TComm.Execute;
var dwEvtMask:Dword;
Wait:Boolean;
begin
FillChar(lpol,SizeOf(lpol),0);
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;
Procedure TForm1.Comminitialize;
var lpdcb:Tdcb;
begin
hcom:=CreateFile('com2', GENERIC_WRITE,0,nil,OPEN_EXISTING,FILE_FLAG_OVERLAPPED,0);
if not (hcom=invalid_handle_value) then
begin
SetupComm(hcom,1024,512);
GetCommState(hcom,lpdcb);
lpdcb.BaudRate:=9600;
lpdcb.StopBits:=1;
lpdcb.ByteSize:=8;
lpdcb.Parity:=EvenParity;
SetCommState(hcom,lpdcb);
SetCommMask(hcom,ev_rxchar);
end;
end;
Procedure TForm1.MsgCommProcess(var message:Tmessage);
var Clear:Boolean;
coms:Tcomstat;
//:Integer;
Read_buffer:array[1..100] of char;
lpErrors,cbnum,readnumber:Dword;
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);
mscomm1.PortOpen:=true;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
mscomm1.Output:='111';
end;
end.
该程序使用了Tmscomm控件,用于向com1发送数据。用一根自制的线连接com1和com2。用api函数接收数据。发现根本截获不了消息!!
再将api接收部分改用tmscomm控件 ,一切正常!
TOverLapped 的等待在com接收就不行可吗? 那么该如何截获这个消息呢?