Author: Tomas Rutkauskas
I'm having a problem sending messages to my threads. I can send back to parent form
very easily with PostMessage, but I have tried to communicate to my threads via
PostMessage and PostThreadMessage to no avail. I read some cryptic remarks in the
PostThreadMessage help that seemed to indicate that I would have to induce the API
into creating a message queue for the thread. Can anyone shed some light?
Answer:
1 type
2 TMyThread = class(TThread)
3 AHwnd: HWND;
4 procedure Execute; override;
5 procedure Terminate;
6 destructor Destroy; override;
7 end;
8
9 procedure TMyThread.Execute;
10 var
11 msg: TMsg;
12 MyTerminated: Boolean;
13 begin
14 MyTerminated := False;
15 while not MyTerminated do
16 begin
17 WaitMessage;
18 if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
19 begin
20 TranslateMessage(Msg);
21 case Msg.message of
22 WM_QUIT: MyTerminated := True;
23 WM_USER: PostMessage(AHwnd, WM_USER, 0, GetTickCount);
24 end;
25 end;
26 end;
27 end;
28
29 procedure TMyThread.Terminate;
30 begin
31 PostThreadMessage(ThreadID, WM_QUIT, 0, 0);
32 inherited;
33 end;
34
35 destructor TMyThread.Destroy;
36 begin
37 Terminate;
38 inherited;
39 end;
40
41 var
42 MyThread: TMyThread;
43
44 procedure TForm1.WMUser(var msg: TMessage); {message WM_USER;}
45 begin
46 Caption := IntToStr(msg.LParam);
47 end;
48
49 procedure TForm1.Button1Click(Sender: TObject);
50 begin
51 MyThread := TMyThread.Create(False);
52 MyThread.AHwnd := Handle;
53 end;
54
55 procedure TForm1.Button2Click(Sender: TObject);
56 begin
57 PostThreadMessage(MyThread.ThreadID, WM_USER, 0, 0);
58 end;
59
60 procedure TForm1.Button3Click(Sender: TObject);
61 begin
62 MyThread.Free;
63 end;
|