用TEvent可以实现程序或线程间的消息通讯,下面是个非常简单的示例,说明
两个程序间通过TEvent通讯的方法。将下面两个Project分别编译,得到两个
EXE文件,运行这两个EXE文件,单击Form2上的Button2,然后切换到Form1单
击Button1,当Form1中的i达到50000时,激发自定义消息,使Form2弹出提示
对话框。这一方法还可用于同一程序中不同线程之间的通信与同步。
Project1:单击Button1后,程序做类加计算,当i达到50000时激发CEV_TEST消息。
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, SyncObjs;
type
TForm1 = class(TForm)
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
CustomEvent: TEvent;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCreate(Sender: TObject);
begin
CustomEvent := TEvent.Create(nil, False, False, 'CEV_TEST');
CustomEvent.ResetEvent;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
i, j: integer;
begin
for i := 1 to 1000000 do
begin
if i > 50000 then
CustomEvent.SetEvent;
j := j + i;
end;
end;
end.
Project2:单击Button2后程序开始等待,如果自定义消息CEV_TEST在10秒内发生
则给出提示信息,否则报告超时。
unit Unit2;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, SyncObjs;
type
TForm2 = class(TForm)
Button2: TButton;
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
CustomEvent: TEvent;
public
{ Public declarations }
end;
var
Form2: TForm2;
implementation
{$R *.DFM}
procedure TForm2.FormCreate(Sender: TObject);
begin
CustomEvent := TEvent.Create(nil, False, False, 'CEV_TEST');
CustomEvent.ResetEvent;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
case CustomEvent.WaitFor(10000) of
wrSignaled: ShowMessage('i reaches 50000');
wrTimeOut: ShowMessage('Time Out');
end;
end;
end.