Delphi - Thread mit Nachricht an das Hauptfenster
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private-Deklarationen }
public
{ Public-Deklarationen }
procedure WndProc(var Msg: TMessage); override;
end;
type
TThreadParams = packed record
FhWnd: THandle;
end;
PThreadParams = ^TThreadParams;
const
MTM_STATUS = WM_USER + 1; // lParam -> Status-String
var
Form1: TForm1;
implementation
{$R *.dfm}
function ThreadFctn(p: Pointer): Integer;
var
i: Integer;
s: String;
hWnd: THandle;
begin
hWnd := PThreadParams(p)^.FhWnd;
for i := 0 to 4 do
begin
s := 'Durchlauf: '+IntToStr(i);
SendMessage(hWnd, MTM_STATUS, 0, Integer(PChar(s)));
sleep(500);
end;
s := 'fertig';
SendMessage(hWnd, MTM_STATUS, 0, Integer(PChar(s)));
FreeMem(p, sizeof(TThreadParams));
result := 0;
end;
procedure TForm1.WndProc(var msg: TMessage);
begin
inherited;
case msg.Msg of
MTM_STATUS:
begin
Caption := PChar(msg.LParam);
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
ThreadParams: PThreadParams;
ThreadID: Cardinal;
begin
GetMem(ThreadParams, sizeof(TThreadParams));
ThreadParams.FhWnd := Handle;
CloseHandle(BeginThread(nil, 0, @ThreadFctn, ThreadParams, 0, ThreadID));
end;
end.