共同讨论:API串口通信问题!

suuare 2003-09-01 10:44:09
部分代码如下:
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接收就不行可吗? 那么该如何截获这个消息呢?

...全文
59 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjqyb 2003-09-02
  • 打赏
  • 举报
回复
不要用mscomm,网上随便一个控件也比用MsComm强
<spcomm,Async32....>
sixgj 2003-09-02
  • 打赏
  • 举报
回复
奇怪……

1,184

社区成员

发帖
与我相关
我的任务
社区描述
Delphi Windows SDK/API
社区管理员
  • Windows SDK/API社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧