//请看下面代码
//一个memo,一个button
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, syncobjs;
const
WM_TEST_MSG = WM_USER+168;
type
// tform1 = class ;
ttestthread = class(tthread)
private
fhwnd:hwnd;
fs:string;
fcount:integer;
procedure wndproc(var msg:tmessage);
procedure addline;
public
destructor destroy;override;
procedure afterconstruction;override;
procedure execute;override;
end;
TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fthread:ttestthread;
public
{ Public declarations }
end;
var
Form1: TForm1;
fcs:trtlcriticalsection;
implementation
{$R *.dfm}
procedure ttestthread.addline;
begin
inc(fcount);
fs:=inttostr(fcount)+' times Thread receive msg WM_TEST_MSG !';
Entercriticalsection(fcs) ;
form1.Memo1.Lines.Add(fs);
leavecriticalsection(fcs);
end;
procedure ttestthread.wndproc(var msg:tmessage);
begin
with msgdo
if Msg = WM_TEST_MSG then
begin
addline;
end
else
result := defwindowproc(fhwnd, msg, wparam, lparam);
end;
destructor ttestthread.destroy;
begin
deallocatehwnd(fhwnd);
inherited destroy;
end;
procedure ttestthread.afterconstruction;
begin
inherited afterconstruction;
fhwnd:=allocatehwnd(wndproc);
fs:='Initial string';
fcount:=0;
end;
procedure ttestthread.execute;
begin
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
sendmessage(fthread.fhwnd ,WM_TEST_MSG,0,0);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
fthread:=ttestthread.Create(false);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
fthread.destroy;
end;
initialization
initializecriticalsection(fcs);
end.