2008. április 28., hétfő

How to send messages to threads


Problem/Question/Abstract:

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:

type
  TMyThread = class(TThread)
    AHwnd: HWND;
    procedure Execute; override;
    procedure Terminate;
    destructor Destroy; override;
  end;

procedure TMyThread.Execute;
var
  msg: TMsg;
  MyTerminated: Boolean;
begin
  MyTerminated := False;
  while not MyTerminated do
  begin
    WaitMessage;
    if PeekMessage(Msg, 0, 0, 0, PM_REMOVE) then
    begin
      TranslateMessage(Msg);
      case Msg.Message of
        WM_QUIT: MyTerminated := True;
        WM_USER: PostMessage(AHwnd, WM_USER, 0, GetTickCount);
      end;
    end;
  end;
end;

procedure TMyThread.Terminate;
begin
  PostThreadMessage(ThreadID, WM_QUIT, 0, 0);
  inherited;
end;

destructor TMyThread.Destroy;
begin
  Terminate;
  inherited;
end;

var
  MyThread: TMyThread;

procedure TForm1.WMUser(var msg: TMessage); {message WM_USER;}
begin
  Caption := IntToStr(msg.LParam);
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  MyThread := TMyThread.Create(False);
  MyThread.AHwnd := Handle;
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  PostThreadMessage(MyThread.ThreadID, WM_USER, 0, 0);
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  MyThread.Free;
end;

Nincsenek megjegyzések:

Megjegyzés küldése